Example usage for com.rabbitmq.client Channel queueDelete

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

Introduction

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

Prototype

Queue.DeleteOk queueDelete(String queue) throws IOException;

Source Link

Document

Delete a queue, without regard for whether it is in use or has messages on it

Usage

From source file:com.vmware.bdd.utils.RabbitMQConsumer.java

License:Open Source License

/**
 * Receive and process each message until the listener indicating. A new
 * queue will be created when start and will be deleted when stopping
 * receiving message./*from   ww  w  .j  a v a2s  .  c  o  m*/
 * 
 * FIXME Is it a best practice to create one queue for one task? Or we should
 * create one thread to handle all messages?
 * 
 * @param listener
 *           message processor callback
 * @throws IOException
 */
public void processMessage(MessageListener listener) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    if (username != null && !username.equals("")) {
        factory.setUsername(username);
        factory.setPassword(password);
    }
    factory.setVirtualHost("/");
    factory.setHost(host);
    factory.setPort(port);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    /**
     * make exchange and queue non-durable
     */
    channel.exchangeDeclare(exchangeName, "direct", true);
    if (!getQueue) {
        channel.queueDeclare(queueName, false, true, true, null);
    } else {
        queueName = channel.queueDeclare().getQueue();
    }
    channel.queueBind(queueName, exchangeName, routingKey);

    boolean noAck = false;
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, noAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery;
        try {
            delivery = consumer.nextDelivery(mqRecvTimeoutMs);
        } catch (InterruptedException e) {
            logger.warn("message consumer interrupted", e);
            continue;
        }

        if (delivery == null) {
            logger.debug("timeout, no message received");
            if (stopping && new Date().after(mqExpireTime)) {
                logger.error("stop receiving messages without normal termination");
                break;
            }
            continue;
        }

        String message = new String(delivery.getBody());
        if (graceStopping) {
            extendExpirationTime();
        }

        logger.info("message received: " + message);
        try {
            if (!listener.onMessage(message)) {
                logger.info("stop receiving messages normally");
                break;
            }
        } catch (Throwable t) {
            logger.error("calling message listener failed", t);
            // discard and continue in non-debug mode
            AuAssert.unreachable();
        }
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

    try {
        channel.queueDelete(queueName);
    } catch (AlreadyClosedException e) {
        logger.error("failed to delete queue: " + queueName, e);
    }

    try {
        channel.close();
    } catch (AlreadyClosedException e) {
        logger.error("failed to close channel, queue: " + queueName, e);
    }

    try {
        conn.close();
    } catch (AlreadyClosedException e) {
        logger.error("failed to close connection, queue: " + queueName, e);
    }
}

From source file:info.pancancer.arch3.reporting.Arch3ReportImpl.java

License:Open Source License

@Override
public Map<String, Status> getLastStatus() {
    String queueName = settings.getString(Constants.RABBIT_QUEUE_NAME);
    final String resultQueueName = queueName + "_results";
    String resultsQueue = null;/*from  w ww.  j av a  2 s.c  o m*/

    Channel resultsChannel = null;
    synchronized (Arch3ReportImpl.this) {
        try {
            // read from
            resultsChannel = Utilities.setupExchange(settings, resultQueueName);
            // this declares a queue exchange where multiple consumers get the same convertToResult:
            // https://www.rabbitmq.com/tutorials/tutorial-three-java.html
            resultsQueue = Utilities.setupQueueOnExchange(resultsChannel, queueName, "SlackReportBot");
            resultsChannel.queueBind(resultsQueue, resultQueueName, "");
            QueueingConsumer resultsConsumer = new QueueingConsumer(resultsChannel);
            resultsChannel.basicConsume(resultsQueue, false, resultsConsumer);

            int messagesToCache = db.getJobs(JobState.RUNNING).size();
            Map<String, Status> cache = new TreeMap<>();

            int loop = 0;
            do {
                loop++;
                QueueingConsumer.Delivery delivery = resultsConsumer
                        .nextDelivery(Base.FIVE_SECOND_IN_MILLISECONDS);
                if (delivery == null) {
                    continue;
                }
                String messageFromQueue = new String(delivery.getBody(), StandardCharsets.UTF_8);
                // now parse it as JSONObj
                Status status = new Status().fromJSON(messageFromQueue);
                cache.put(status.getIpAddress(), status);
            } while (loop < LOOP_LIMIT && cache.size() < messagesToCache);

            return cache;

        } catch (IOException | ShutdownSignalException | InterruptedException | TimeoutException
                | ConsumerCancelledException ex) {
            throw new RuntimeException(ex);
        } finally {
            try {
                if (resultsQueue != null && resultsChannel != null) {
                    resultsChannel.queueDelete(resultsQueue);
                }
                if (resultsChannel != null) {

                    resultsChannel.close();
                    resultsChannel.getConnection().close();
                }
            } catch (IOException | TimeoutException ex) {
                System.err.println("Could not close channel");
            }
        }
    }
}

From source file:info.pancancer.arch3.utils.Utilities.java

License:Open Source License

/**
 * Clears database state and known queues for testing.
 *
 * @param settings/*from  www.jav a  2s  . c  o  m*/
 * @throws IOException
 * @throws java.util.concurrent.TimeoutException
 */
public static void clearState(HierarchicalINIConfiguration settings) throws IOException, TimeoutException {
    File configFile = FileUtils.getFile("src", "test", "resources", "config");
    HierarchicalINIConfiguration parseConfig = Utilities.parseConfig(configFile.getAbsolutePath());
    PostgreSQL postgres = new PostgreSQL(parseConfig);
    // clean up the database
    postgres.clearDatabase();

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel;

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(server);
    factory.setUsername(user);
    factory.setPassword(pass);
    factory.setAutomaticRecoveryEnabled(true);
    Connection connection = factory.newConnection();
    channel = connection.createChannel();
    channel.basicQos(1);
    channel.confirmSelect();

    String prefix = settings.getString(Constants.RABBIT_QUEUE_NAME);
    String[] queues = { prefix + "_jobs", prefix + "_orders", prefix + "_vms", prefix + "_for_CleanupJobs",
            prefix + "_for_CleanupVMs" };
    for (String queue : queues) {
        try {
            channel.queueDelete(queue);
        } catch (IOException e) {
            Log.info("Could not delete " + queue);
        }
    }
}

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

License:Apache License

public static void delete(Channel channel, String queue) throws IOException {
    channel.queueDelete(queue);
}

From source file:joram.amqp.PersistenceKillTest.java

License:Open Source License

public void killingTest() throws Exception {
    senderConnection = new LiveServerConnection("sender", "localhost", 5672, null, null);
    receiverConnection = new LiveServerConnection("receiver", "localhost", 5672, null, null);

    senderConnection.startLiveConnection();
    receiverConnection.startLiveConnection();

    Channel senderChannel = senderConnection.getConnection().createChannel();
    senderChannel.txSelect();//from w ww  .j  a  v  a  2  s . c o m

    DeclareOk declareOk = senderChannel.queueDeclare("testQueue", true, false, false, null);

    new Thread(new Runnable() {

        int received;
        long totalReceived;

        Channel consumerChannel;
        QueueingConsumer consumer;

        // Consumer thread
        public void run() {

            try {
                consumerChannel = receiverConnection.getConnection().createChannel();
                consumerChannel.txSelect();
                consumer = new QueueingConsumer(consumerChannel);
                consumerChannel.basicConsume("testQueue", false, consumer);
            } catch (Exception exc) {
                exc.printStackTrace();
            }

            while (true) {
                QueueingConsumer.Delivery delivery;
                try {
                    delivery = consumer.nextDelivery();
                    long receivedNb = Long.parseLong(new String(delivery.getBody()));
                    consumer.getChannel().basicAck(delivery.getEnvelope().getDeliveryTag(), false);

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException exc1) {
                    }

                    if (receivedNb < totalReceived) {
                        System.out.println("Duplicate received: " + receivedNb);
                        continue;
                    }

                    // We can receive duplicates but can't miss one message
                    // One duplicate if the channel is transacted, multiple if it is not
                    assertEquals(totalReceived, receivedNb);

                    totalReceived++;
                    received++;

                    consumerChannel.txCommit();

                    if (received == nbMsgRound) {
                        received = 0;
                        synchronized (lock) {
                            lock.notify();
                        }
                    }

                    if (totalReceived == nbMsgRound * nbRounds) {
                        consumer.getChannel().close();
                        return;
                    }

                } catch (Exception ie) {
                    if (totalReceived == nbRounds * nbMsgRound) {
                        return;
                    }
                    System.out.println("Consumer connection broken. Reconnect.");
                    while (!receiverConnection.isConnectionOpen()) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException exc) {
                            exc.printStackTrace();
                        }
                    }
                    try {
                        consumerChannel = receiverConnection.getConnection().createChannel();
                        consumerChannel.txSelect();
                        consumer = new QueueingConsumer(consumerChannel);
                        consumerChannel.basicConsume("testQueue", false, consumer);
                    } catch (IOException exc) {
                        exc.printStackTrace();
                    }
                    System.out.println("Consumer Reconnected --- totalReceived = " + totalReceived);
                    continue;
                }
            }
        }
    }).start();

    long start = System.nanoTime();

    // Killer thread
    new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(5000);
                System.out.println("Kill server");
                killAgentServer((short) 0);

                Thread.sleep(5000);
                startAgentServer((short) 0);
                System.out.println("server restarted.");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }).start();

    // Sender
    for (int i = 0; i < nbRounds; i++) {
        if (i % 20 == 0) {
            long delta = System.nanoTime() - start;
            System.out.println("Round " + i + " " + ((i * nbMsgRound * 1000000000L) / delta) + " msg/s");
        }
        try {
            for (int j = 0; j < nbMsgRound; j++) {
                senderChannel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                        new Long(i * nbMsgRound + j).toString().getBytes());
            }

            synchronized (lock) {
                senderChannel.txCommit();
                lock.wait();
            }
        } catch (Exception exc) {
            i--;
            System.out.println("Sender connection broken. Reconnect.");
            while (!senderConnection.isConnectionOpen()) {
                Thread.sleep(100);
            }
            senderChannel = senderConnection.getConnection().createChannel();
            senderChannel.txSelect();
            System.out.println("Sender Reconnected");
            Thread.sleep(1000);
            System.out.println("Restart Sender");
        }
    }

    long delta = System.nanoTime() - start;
    System.out.println(delta / 1000000L + " ms");
    System.out.println(((nbRounds * nbMsgRound * 1000000000L) / delta) + " msg/s");

    senderChannel.queueDelete(declareOk.getQueue());

    senderChannel.close();

    senderConnection.stopLiveConnection();
    receiverConnection.stopLiveConnection();

}

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();/*ww w .ja  v a 2  s. c om*/
    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();//from  ww w  .j av  a 2 s. com
    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:net.echinopsii.ariane.community.messaging.rabbitmq.ServiceFactory.java

License:Open Source License

/**
 * (internal usage)//from www  . j a v a2 s  . c  om
 * Create a new MomConsumer to consume message from RabbitMQ source and forward them to the request actor.
 *
 * @param source request source queue
 * @param channel RabbitMQ channel
 * @param requestActor request actor ref to treat the message
 * @param isMsgDebugOnTimeout debug on timeout if true
 * @return the new MomConsumer
 */
private static MomConsumer createConsumer(final String source, final Channel channel,
        final ActorRef requestActor, final boolean isMsgDebugOnTimeout) {
    return new MomConsumer() {
        private boolean isRunning = false;

        @Override
        public void run() {
            try {
                Map<String, Object> finalMessage;
                channel.queueDeclare(source, false, false, true, null);

                QueueingConsumer consumer = new QueueingConsumer(channel);
                channel.basicConsume(source, false, consumer);
                isRunning = true;

                while (isRunning) {
                    try {
                        QueueingConsumer.Delivery delivery = consumer.nextDelivery(10);
                        if (delivery != null && isRunning) {
                            finalMessage = translator.decode(new Message().setEnvelope(delivery.getEnvelope())
                                    .setProperties(delivery.getProperties()).setBody(delivery.getBody()));
                            if (((HashMap) finalMessage).containsKey(MomMsgTranslator.MSG_TRACE)
                                    && isMsgDebugOnTimeout)
                                ((MomLogger) log).setMsgTraceLevel(true);
                            ((MomLogger) log).traceMessage("MomConsumer(" + source + ").run", finalMessage);
                            requestActor.tell(delivery, null);
                            if (((HashMap) finalMessage).containsKey(MomMsgTranslator.MSG_TRACE)
                                    && isMsgDebugOnTimeout)
                                ((MomLogger) log).setMsgTraceLevel(false);
                        }
                    } catch (InterruptedException e) {
                        // no message
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (channel.getConnection() != null && channel.getConnection().isOpen()) {
                        channel.queueDelete(source);
                        //channel.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public boolean isRunning() {
            return isRunning;
        }

        @Override
        public void start() {
            new Thread(this).start();
        }

        @Override
        public void stop() {
            isRunning = false;
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
}

From source file:net.es.netshell.rabbitmq.Box.java

License:Open Source License

public String queryQueue(String sendQueue, String token, Channel channel, String symLink) throws Exception {

    // Create random UUID for producer's temporary queue
    String uuid = UUID.randomUUID().toString();
    // Declare this temporary queue and start listening (exclusive queue).
    channel.queueDeclare(uuid, false, true, true, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);

    // Send TOKEN_REQUEST with curent username.
    String message = token + ":QUEUE_QUERY" + ":" + uuid + ":"
            + KernelThread.currentKernelThread().getUser().getName() + ":" + symLink;

    channel.basicPublish("", sendQueue, null, message.getBytes());
    // Start consuming to receive token.
    channel.basicConsume(uuid, true, "tokenRequest", false, true, null, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();

    // When token is received, store in "token."
    String queueName = new String(delivery.getBody());
    // Delete temporary queue
    channel.queueDelete(uuid);

    return queueName;

}

From source file:net.es.netshell.rabbitmq.Consume.java

License:Open Source License

public void consumeMessage() throws Exception {
    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }/*  w ww.  j av  a  2s.co  m*/
    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(queueName, false, false, true, null);
    System.out.println(" [*] Waiting for messages.");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, "consumer", false, false, null, consumer);

    //while (true) {
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
    ByteArrayInputStream bais = new ByteArrayInputStream(delivery.getBody());
    ObjectInputStream in = new ObjectInputStream(bais);
    DefaultListenableGraph g = (DefaultListenableGraph) in.readObject();
    System.out.println(" [x] Received Message");

    // GraphViewer view = new GraphViewer(g);
    // view.init();

    //         if (message.substring(0,13).equals("TOKEN_REQUEST")) {
    //            String[] token = new ProcessTokenRequest(message, channel).sendToken();
    //            permissions.put(token[0], token[1]);
    //            //String[] messageSplit = message.split(":");
    //            //sendToken(messageSplit[1], messageSplit[2], channel);
    //         } else {
    //            String[] messageSplit = message.split(":", 2);
    //            if (permissions.containsKey(messageSplit[0])) {
    //               System.out.println(" [x] Received '" + messageSplit[1] + "' from: " + permissions.get(messageSplit[0]));
    //            } else {
    //               System.out.println(" ERROR: INVALID TOKEN PROVIDED IN MESSAGE");
    //            }
    //         }
    //}

    channel.queueDelete(queueName);
    channel.close();
    connection.close();
}