Example usage for com.rabbitmq.client Channel queuePurge

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

Introduction

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

Prototype

Queue.PurgeOk queuePurge(String queue) throws IOException;

Source Link

Document

Purges the contents of the given queue.

Usage

From source file:br.uff.labtempo.omcp.common.utils.RabbitComm.java

License:Apache License

public void purgeQueueOrDie(String queueName) throws UnreachableModuleException {
    try {//from  w  w w .  java  2 s  . co m
        Channel ch = connection.createChannel();
        ch.queuePurge(queueName);
        ch.close();
    } catch (Exception e) {
        throw new UnreachableModuleException("Could not purge queue!");
    }
}

From source file:org.ballerinalang.messaging.rabbitmq.util.ChannelUtils.java

License:Open Source License

/**
 * Purges a queue./*  w  ww  .j a  v a2s . c  o  m*/
 *
 * @param channel   RabbitMQ Channel object.
 * @param queueName Name of the queue.
 */
public static void queuePurge(Channel channel, String queueName) {
    try {
        channel.queuePurge(queueName);
    } catch (IOException exception) {
        String errorMessage = "An error occurred while purging the queue ";
        throw new RabbitMQConnectorException(errorMessage + exception.getMessage(), exception);
    }
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQIntegrationTest.java

License:Apache License

private void launchTest(XContentBuilder river, final int numMessages, final int numDocsPerMessage,
        InjectorHook injectorHook, boolean delete, boolean update) throws Exception {

    final String dbName = getDbName();
    logger.info(" --> create index [{}]", dbName);
    try {/*from w  w  w. j  ava2s .c  o m*/
        client().admin().indices().prepareDelete(dbName).get();
    } catch (IndexMissingException e) {
        // No worries.
    }
    try {
        createIndex(dbName);
    } catch (IndexMissingException e) {
        // No worries.
    }
    ensureGreen(dbName);

    logger.info("  -> Checking rabbitmq running");
    // We try to connect to RabbitMQ.
    // If it's not launched, we don't fail the test but only log it
    Channel channel = null;
    Connection connection = null;
    try {
        logger.info(" --> connecting to rabbitmq");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(AMQP.PROTOCOL.PORT);
        connection = factory.newConnection();
    } catch (ConnectException ce) {
        throw new Exception("RabbitMQ service is not launched on localhost:" + AMQP.PROTOCOL.PORT
                + ". Can not start Integration test. " + "Launch `rabbitmq-server`.", ce);
    }

    try {
        logger.info("  -> Creating [{}] channel", dbName);
        channel = connection.createChannel();

        logger.info("  -> Creating queue [{}]", dbName);
        channel.queueDeclare(getDbName(), true, false, false, null);

        // We purge the queue in case of something is remaining there
        logger.info("  -> Purging [{}] channel", dbName);
        channel.queuePurge(getDbName());

        logger.info("  -> Put [{}] messages with [{}] documents each = [{}] docs", numMessages,
                numDocsPerMessage, numMessages * numDocsPerMessage);
        final Set<String> removed = new HashSet<String>();
        int nbUpdated = 0;
        for (int i = 0; i < numMessages; i++) {
            StringBuffer message = new StringBuffer();

            for (int j = 0; j < numDocsPerMessage; j++) {
                if (logger.isTraceEnabled()) {
                    logger.trace("  -> Indexing document [{}] - [{}][{}]", i + "_" + j, i, j);
                }
                message.append("{ \"index\" : { \"_index\" : \"" + dbName
                        + "\", \"_type\" : \"typex\", \"_id\" : \"" + i + "_" + j + "\" } }\n");
                message.append("{ \"field\" : \"" + i + "_" + j + "\",\"numeric\" : " + i * j + " }\n");

                // Sometime we update a document
                if (update && rarely()) {
                    String id = between(0, i) + "_" + between(0, j);
                    // We can only update if it has not been removed :)
                    if (!removed.contains(id)) {
                        logger.debug("  -> Updating document [{}] - [{}][{}]", id, i, j);
                        message.append("{ \"update\" : { \"_index\" : \"" + dbName
                                + "\", \"_type\" : \"typex\", \"_id\" : \"" + id + "\" } }\n");
                        message.append(
                                "{ \"doc\": { \"foo\" : \"bar\", \"field2\" : \"" + i + "_" + j + "\" }}\n");
                        nbUpdated++;
                    }
                }

                // Sometime we delete a document
                if (delete && rarely()) {
                    String id = between(0, i) + "_" + between(0, j);
                    if (!removed.contains(id)) {
                        logger.debug("  -> Removing document [{}] - [{}][{}]", id, i, j);
                        message.append("{ \"delete\" : { \"_index\" : \"" + dbName
                                + "\", \"_type\" : \"typex\", \"_id\" : \"" + id + "\" } }\n");
                        removed.add(id);
                    }
                }
            }

            channel.basicPublish("", dbName, null, message.toString().getBytes());
        }

        logger.info("  -> We removed [{}] docs and updated [{}] docs", removed.size(), nbUpdated);

        if (injectorHook != null) {
            logger.info("  -> Injecting extra data");
            injectorHook.inject();
        }

        logger.info(" --> create river");
        IndexResponse indexResponse = index("_river", dbName, "_meta", river);
        assertTrue(indexResponse.isCreated());

        logger.info("-->  checking that river [{}] was created", dbName);
        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                GetResponse response = client()
                        .prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
                return response.isExists();
            }
        }, 5, TimeUnit.SECONDS), equalTo(true));

        // Check that docs are still processed by the river
        logger.info(" --> waiting for expected number of docs: [{}]",
                numDocsPerMessage * numMessages - removed.size());
        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                try {
                    refresh();
                    int expected = numDocsPerMessage * numMessages - removed.size();
                    CountResponse response = client().prepareCount(dbName).get();
                    logger.debug("  -> got {} docs, expected {}", response.getCount(), expected);
                    return response.getCount() == expected;
                } catch (IndexMissingException e) {
                    return false;
                }
            }
        }, 20, TimeUnit.SECONDS), equalTo(true));
    } finally {
        if (channel != null && channel.isOpen()) {
            channel.close();
        }
        if (connection != null && connection.isOpen()) {
            connection.close();
        }

        // Deletes the river
        GetResponse response = client().prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status")
                .get();
        if (response.isExists()) {
            client().prepareDelete(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_meta").get();
            client().prepareDelete(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
        }

        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                GetResponse response = client()
                        .prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
                return response.isExists();
            }
        }, 5, TimeUnit.SECONDS), equalTo(false));
    }
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQTestRunner.java

License:Apache License

@Test
public void test_all_messages_are_consumed() throws Exception {

    // We try to connect to RabbitMQ.
    // If it's not launched, we don't fail the test but only log it
    try {//from   w  w w .ja  va  2s  . com
        logger.info(" --> connecting to rabbitmq");
        ConnectionFactory cfconn = new ConnectionFactory();
        cfconn.setHost("localhost");
        cfconn.setPort(AMQP.PROTOCOL.PORT);
        Connection conn = cfconn.newConnection();

        Channel ch = conn.createChannel();
        ch.exchangeDeclare("elasticsearch", "direct", true);
        AMQP.Queue.DeclareOk queue = ch.queueDeclare("elasticsearch", true, false, false, null);

        // We purge the queue in case of something is remaining there
        ch.queuePurge("elasticsearch");

        logger.info(" --> sending messages");
        pushMessages(ch);

        logger.info(" --> create river");
        createIndex(INDEX);

        index("_river", "test", "_meta", river());

        // We need at some point to check if we have consumed the river
        int steps = timeout();
        long count = 0;

        while (true) {
            // We wait for one second
            Thread.sleep(1000);

            CountResponse response = client().prepareCount("test").execute().actionGet();
            count = response.getCount();

            steps--;
            if (steps < 0 || count == expectedDocuments()) {
                break;
            }
        }

        ch.close();
        conn.close();

        postInjectionTests();
    } catch (ConnectException e) {
        throw new Exception("RabbitMQ service is not launched on localhost:" + AMQP.PROTOCOL.PORT
                + ". Can not start Integration test. " + "Launch `rabbitmq-server`.", e);
    }
}

From source file:org.mule.transport.amqp.harness.rules.AmqpModelRule.java

License:Open Source License

protected void applyQueuesConfiguration(Configuration configuration, Channel channel) throws IOException {
    List<Queue> configurationQueues = configuration.getQueues();

    for (Queue queue : configurationQueues) {
        channel.queueDeclare(queue.getName(), queue.isDurable(), false, queue.isAutoDelete(),
                new HashMap<String, Object>());
        channel.queuePurge(queue.getName());
    }//from  w  ww. jav a2s  .  c  o m
}

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

License:Apache License

@Override
@ManagedOperation/*from w  w  w. j a  v a  2s .c o  m*/
public void purgeQueue(final String queueName, final boolean noWait) {
    this.rabbitTemplate.execute(new ChannelCallback<Object>() {
        @Override
        public Object doInRabbit(Channel channel) throws Exception {
            channel.queuePurge(queueName);
            return null;
        }
    });
}

From source file:pl.nask.hsn2.bus.rabbitmq.RbtUtils.java

License:Open Source License

/**
 * Removed all messages from the queue./* w  ww  . j a  v a 2s.  c  o m*/
 * 
 * @param connection Connection to Rabbit MQ server.
 * @param queueName Name of the queue to be purged.
 */
public static void purgeQueue(Channel channel, String queueName) {
    try {
        channel.queuePurge(queueName);
    } catch (IOException ex) {
        LOGGER.error("Error during purging queue: {}", queueName);
    }
}