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:com.trivago.mail.pigeon.web.data.process.QueueNewsletter.java

License:Apache License

public int getProgress(long newsletterId) {
    Connection conn = ConnectionPool.getConnection();
    Channel channel = null;
    try {//from   w  w  w  .  j ava2  s  .c  o  m
        channel = conn.createChannel();
        AMQP.Queue.DeclareOk declareOk = channel.queueDeclarePassive(channelName);
        return declareOk.getMessageCount();
    } catch (Exception e) {
        log.error("Error while fetching progress", e);
    } finally {
        assert channel != null;
        try {
            channel.close();
        } catch (IOException e) {
            log.error("Could not close channel", e);
        }
    }
    return 0;
}

From source file:com.UseCaseSimpleConsumer.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {/*from  w w w  . java  2  s .c o m*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }
    try {
        channel.queueDeclarePassive(ROUTE_KEY);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(ROUTE_KEY, false, false, false, null);
    }

    channel.queueBind(ROUTE_KEY, EXCHANGE_NAME, ROUTE_KEY);

    String param = "IBM";
    String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + "    <m:order>\n"
            + "        <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + "        <m:quantity>"
            + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + "        <m:symbol>" + param
            + "</m:symbol>\n" + "    </m:order>\n" + "</m:placeOrder>";

    channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY,
            new AMQP.BasicProperties.Builder().contentType("text/plain").build(), msg.getBytes());
    System.out.println(" [x] Sent '" + msg + "'");
    channel.close();
    connection.close();
}

From source file:com.UseCaseSimpleProducer.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {/*www  . ja  va2  s  . c om*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
    }
}

From source file:com.viadeo.kasper.core.component.event.eventbus.EventMessageHandlerITest.java

License:Open Source License

protected int getQueueSize(final String name) {
    return rabbitAdmin.getRabbitTemplate().execute(new ChannelCallback<AMQP.Queue.DeclareOk>() {
        public AMQP.Queue.DeclareOk doInRabbit(Channel channel) throws Exception {
            return channel.queueDeclarePassive(name);
        }// w  ww .  j  a  v a2 s.c  o m
    }).getMessageCount();
}

From source file:it.txt.ens.authorisationService.amqp.AMQPQueueHelper.java

License:Apache License

public static boolean exists(Channel channel, String queue) {
    try {/*from w  ww . j  av a 2s  . c  o  m*/
        channel.queueDeclarePassive(queue);
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:jenkins.plugins.logstash.persistence.RabbitMqDao.java

License:Open Source License

@Override
public void push(String data) throws IOException {
    Connection connection = null;
    Channel channel = null;
    try {//from   w ww  .j  a  v a  2s. c om
        connection = pool.newConnection();
        channel = connection.createChannel();

        // Ensure the queue exists
        try {
            channel.queueDeclarePassive(key);
        } catch (IOException e) {
            // The queue does not exist and the channel has been closed
            finalizeChannel(channel);

            // Create the queue
            channel = connection.createChannel();
            channel.queueDeclare(key, true, false, false, null);
        }

        channel.basicPublish("", key, null, data.getBytes());
    } finally {
        finalizeChannel(channel);
        finalizeConnection(connection);
    }
}

From source file:joram.amqp.PersistenceSimpleTest.java

License:Open Source License

public void recover1() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    channel.txSelect();//from   w w w  .  j a va2s .  co  m
    for (int i = 0; i < 5; i++) {
        channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                "this is a test message !!!".getBytes());
    }
    channel.txCommit();

    killAgentServer((short) 0);

    startAgentServer((short) 0);

    connection = cnxFactory.newConnection();
    channel = connection.createChannel();
    declareOk = channel.queueDeclarePassive("testqueue");

    for (int i = 0; i < 5; i++) {
        GetResponse msg = channel.basicGet("testqueue", true);
        assertNotNull(msg);
        assertEquals("this is a test message !!!", new String(msg.getBody()));
    }

    GetResponse msg = channel.basicGet("testqueue", true);
    assertNull(msg);

    channel.queueDelete(declareOk.getQueue());
}

From source file:joram.amqp.PersistenceSimpleTest.java

License:Open Source License

public void recover2() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    channel.txSelect();/*ww  w .jav a  2  s . c  o m*/
    for (int i = 0; i < 5; i++) {
        channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                "this is a test message !!!".getBytes());
    }
    channel.txCommit();

    killAgentServer((short) 0);

    startAgentServer((short) 0);
    Thread.sleep(500);

    connection = cnxFactory.newConnection();
    channel = connection.createChannel();
    declareOk = channel.queueDeclarePassive("testqueue");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(declareOk.getQueue(), true, consumer);

    for (int i = 0; i < 5; i++) {
        Delivery msg = consumer.nextDelivery(1000);
        assertNotNull(msg);
        assertEquals("this is a test message !!!", new String(msg.getBody()));
    }

    Delivery msg = consumer.nextDelivery(1000);
    assertNull(msg);

    channel.queueDelete(declareOk.getQueue());

}

From source file:mobisocial.musubi.service.AMQPService.java

License:Apache License

void attachToQueues() throws IOException {
    Log.i(TAG, "Setting up identity exchange and device queue");

    DefaultConsumer consumer = new DefaultConsumer(mIncomingChannel) {
        @Override/*  w w  w  .  j  av  a2 s  . c  o  m*/
        public void handleDelivery(final String consumerTag, final Envelope envelope,
                final BasicProperties properties, final byte[] body) throws IOException {
            if (DBG)
                Log.i(TAG, "recevied message: " + envelope.getExchange());
            assert (body != null);
            //TODO: throttle if we have too many incoming?
            //TODO: check blacklist up front?
            //TODO: check hash up front?
            MEncodedMessage encoded = new MEncodedMessage();
            encoded.encoded_ = body;
            mEncodedMessageManager.insertEncoded(encoded);
            getContentResolver().notifyChange(MusubiService.ENCODED_RECEIVED, null);

            //we have to do this in our AMQP thread, or add synchronization logic
            //for all of the AMQP related fields.
            mAMQPHandler.post(new Runnable() {
                public void run() {
                    if (mIncomingChannel == null) {
                        //it can close in this time window
                        return;
                    }
                    try {
                        mIncomingChannel.basicAck(envelope.getDeliveryTag(), false);
                        if (mFailedOperation == FailedOperationType.FailedReceive) {
                            mFailureDelay = MIN_DELAY;
                            mFailedOperation = FailedOperationType.FailedNone;
                        }
                    } catch (Throwable e) {
                        Log.e(TAG, "failed to ack message on AMQP", e);
                        //next connection that receives a packet wins
                        closeConnection(FailedOperationType.FailedReceive);
                    }

                }
            });
        }
    };
    byte[] device_name = new byte[8];
    ByteBuffer.wrap(device_name).putLong(mDeviceManager.getLocalDeviceName());
    String device_queue_name = encodeAMQPname("ibedevice-", device_name);
    //leaving these since they mark the beginning of the connection and shouldn't be too frequent (once per drop)
    Log.v(TAG, "queueDeclare " + device_queue_name);
    mIncomingChannel.queueDeclare(device_queue_name, true, false, false, null);
    //TODO: device_queue_name needs to involve the identities some how? or be a larger byte array
    List<MIdentity> mine = mIdentitiesManager.getOwnedIdentities();
    for (MIdentity me : mine) {
        IBHashedIdentity id = IdentitiesManager.toIBHashedIdentity(me, 0);
        String identity_exchange_name = encodeAMQPname("ibeidentity-", id.identity_);
        Log.v(TAG, "exchangeDeclare " + identity_exchange_name);
        mIncomingChannel.exchangeDeclare(identity_exchange_name, "fanout", true);
        Log.v(TAG, "queueBind " + device_queue_name + " " + identity_exchange_name);
        mIncomingChannel.queueBind(device_queue_name, identity_exchange_name, "");
        try {
            Log.v(TAG, "queueDeclarePassive " + "initial-" + identity_exchange_name);
            Channel incoming_initial = mConnection.createChannel();
            incoming_initial.queueDeclarePassive("initial-" + identity_exchange_name);
            try {
                Log.v(TAG, "queueUnbind " + "initial-" + identity_exchange_name + " " + identity_exchange_name);
                //   we now have claimed our identity, unbind this queue
                incoming_initial.queueUnbind("initial-" + identity_exchange_name, identity_exchange_name, "");
                //but also drain it
            } catch (IOException e) {
            }
            Log.v(TAG, "basicConsume " + "initial-" + identity_exchange_name);
            mIncomingChannel.basicConsume("initial-" + identity_exchange_name, consumer);
        } catch (IOException e) {
            //no one sent up messages before we joined
            //IF we deleted it: we already claimed our identity, so we ate this queue up
        }
    }

    Log.v(TAG, "basicConsume " + device_queue_name);
    mIncomingChannel.basicConsume(device_queue_name, false, "", true, true, null, consumer);
}

From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java

License:Apache License

@Test
public void onlyPutWhenInQualifierFilter() throws Exception {

    Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg",
            "a", amq_default_address, primaryTableNameString, "false", "some_key");
    setupHBase(kvs);/*from www .j  a v a2s  .  c  o m*/

    //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());
    tablePut.addColumn("e".getBytes(), "other_key".getBytes(), "some_value".getBytes());
    tablePut.addColumn("e".getBytes(), "third_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("Test: connecting to %s", primaryTableNameString));

    while (true) {
        int numMessages = channel.queueDeclarePassive(primaryTableNameString).getMessageCount();
        GetResponse response = channel.basicGet(primaryTableNameString, false);
        if (response == null || numMessages == 0)//busy-wait until the message has made it through the MQ
        {
            continue;
        }
        Assert.assertEquals("There should be only a single key in the queue", 1, numMessages);
        String routingKey = response.getEnvelope().getRoutingKey();
        Assert.assertEquals("Routing key should be rowkey", "genome", routingKey);

        String contentType = response.getProps().getContentType();
        Assert.assertEquals("Content type should be preserved", "application/json", contentType);

        Map<String, Object> headers = response.getProps().getHeaders();
        Assert.assertEquals("An action should be set on the message", "put", headers.get("action").toString());

        byte[] body = response.getBody();

        JSONObject jo = new JSONObject(new String(body));
        String column_family = (String) jo.get("column_family");
        Assert.assertEquals("Column family should be preserved in the message body", "eg", column_family);

        String column_value = (String) jo.get("column_value");
        Assert.assertEquals("Column value is not sent by default", "", column_value);

        long deliveryTag = response.getEnvelope().getDeliveryTag();
        channel.basicAck(deliveryTag, false);
        break;
    }
}