Example usage for com.rabbitmq.client Channel abort

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

Introduction

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

Prototype

void abort() throws IOException;

Source Link

Document

Abort this channel with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

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
 *///from  ww w.jav a  2  s.c o 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.cloudstack.mom.rabbitmq.RabbitMQEventBus.java

License:Apache License

@Override
public boolean stop() {

    if (_connection.isOpen()) {
        for (String subscriberId : _subscribers.keySet()) {
            Ternary<String, Channel, EventSubscriber> subscriberDetails = _subscribers.get(subscriberId);
            Channel channel = subscriberDetails.second();
            String queueName = subscriberId;
            try {
                channel.queueDelete(queueName);
                channel.abort();
            } catch (IOException ioe) {
                s_logger.warn(/*from   ww w.  j  a v  a2  s .c  o  m*/
                        "Failed to delete queue: " + queueName + " on AMQP server due to " + ioe.getMessage());
            }
        }
    }

    closeConnection();
    return true;
}

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

License:Open Source License

/**
 * Aborts the channel.//from  w ww . j av a2  s .c om
 *
 * @param channel RabbitMQ Channel object.
 * @throws IOException If an I/O problem is encountered.
 */
public static void abort(Channel channel) throws IOException {
    channel.abort();
}

From source file:org.teksme.server.queue.sender.impl.AMQPQueueSenderService.java

License:Apache License

public void closeChannel(Channel channel) throws IOException {
    if (channel != null) {
        channel.abort();
        channel = null;//from w  w w. jav a 2  s . c  o  m
    }
}

From source file:vn.com.uet.performance.rabbitmq.MulticastParams.java

License:Open Source License

public String configureQueue(Connection connection, String id) throws IOException {
    Channel channel = connection.createChannel();
    if (!predeclared || !exchangeExists(connection, exchangeName)) {
        channel.exchangeDeclare(exchangeName, exchangeType);
    }//from   www .  j  a  v  a  2  s.co m
    String qName = queueName;
    if (!predeclared || !queueExists(connection, queueName)) {
        qName = channel.queueDeclare(queueName, flags.contains("persistent"), false, autoDelete, null)
                .getQueue();
    }
    channel.queueBind(qName, exchangeName, id);
    channel.abort();
    return qName;
}

From source file:vn.com.uet.performance.rabbitmq.MulticastParams.java

License:Open Source License

private static boolean exists(Connection connection, Checker checker) throws IOException {
    try {/*from  w  w  w.j  a va  2s  . c o m*/
        Channel ch = connection.createChannel();
        checker.check(ch);
        ch.abort();
        return true;
    } catch (IOException e) {
        ShutdownSignalException sse = (ShutdownSignalException) e.getCause();
        if (!sse.isHardError()) {
            AMQP.Channel.Close closeMethod = (AMQP.Channel.Close) sse.getReason();
            if (closeMethod.getReplyCode() == AMQP.NOT_FOUND) {
                return false;
            }
        }
        throw e;
    }
}

From source file:xyz.cloudbans.barker.amqp.AmqpBarkerTest.java

License:Apache License

@Test
public void testConsume() throws Throwable {
    Channel channel = openChannel();
    AmqpBarkerOptions options = createOptions();
    Barker barker = new AmqpBarker(channel, options);
    final CountDownLatch countDownLatch = new CountDownLatch(4);
    final AtomicInteger counter = new AtomicInteger();
    final AtomicBoolean failed = new AtomicBoolean();

    barker.subscribe(TOPIC_NAME, new BarkerListener() {
        @Override//from   w  ww.  j av  a2s.co  m
        public void onMessage(Subscription subscription, Message message) {
            if (!"test".equals(subscription.getTopic()) || !new String(message.getBody()).startsWith("Test"))
                failed.set(true);
            countDownLatch.countDown();
            counter.incrementAndGet();
            message.acknowledge();
        }
    });

    for (int i = 0; i < 4; i++)
        barker.submit(TOPIC_NAME, ("Test #" + i).getBytes());

    countDownLatch.await();
    // Wait  a short moment for possible more messages
    Thread.sleep(100);

    Assert.assertFalse(failed.get());
    Assert.assertEquals(4, counter.get());

    cleanup(options, channel);
    channel.abort();
}

From source file:xyz.cloudbans.barker.amqp.AmqpBarkerTest.java

License:Apache License

@Test
public void testOneTimeConsume() throws Throwable {
    Channel channel = openChannel();
    AmqpBarkerOptions options = createOptions();
    Barker barker = new AmqpBarker(channel, options);
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final AtomicInteger counter = new AtomicInteger();
    final AtomicBoolean failed = new AtomicBoolean();

    barker.subscribe(TOPIC_NAME, new OneTimeListener() {
        @Override/* w w  w  .j a  v  a 2 s. c  om*/
        protected boolean handleMessage(Subscription subscription, Message message) {
            if (!"test".equals(subscription.getTopic()) || !new String(message.getBody()).equals("Test"))
                failed.set(true);
            countDownLatch.countDown();
            counter.incrementAndGet();
            return true;
        }
    });

    for (int i = 0; i < 2; i++)
        barker.submit(TOPIC_NAME, "Test".getBytes());

    countDownLatch.await();
    // Wait  a short moment for possible more messages
    Thread.sleep(100);

    Assert.assertFalse(failed.get());
    Assert.assertEquals(1, counter.get());

    cleanup(options, channel);
    channel.abort();
}