Example usage for com.rabbitmq.client Channel close

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

Introduction

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

Prototype

@Override
void close() throws IOException, TimeoutException;

Source Link

Document

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

Usage

From source file:org.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPTopicSenderImpl.java

License:Apache License

public void Send(OMElement message) throws AMQPException {
    try {/*from  ww  w.j  a v a 2  s  . c om*/
        if (isRoutable(message)) {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_TOPIC, AMQPUtil.EXCHANGE_TYPE_TOPIC);

            List<String> routingKeys = new ArrayList<String>();
            getRoutingKeys(message, routingKeys);

            for (String routingKey : routingKeys) {
                channel.basicPublish(AMQPUtil.EXCHANGE_NAME_TOPIC, routingKey, null,
                        message.toString().getBytes());
            }

            channel.close();
            connection.close();
        }
    } catch (IOException e) {
        throw new AMQPException(e);
    }
}

From source file:org.apache.axis2.transport.amqp.out.AMQPSender.java

License:Apache License

/**
 * Performs the actual sending of the AMQP message
 *//*w  ww  . ja v a2 s .  c  o  m*/
@Override
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    AMQPConnectionFactory conFac = null;
    AMQPTransportInfo amqpOut = null;
    AMQPMessageSender messageSender = null;
    Connection con = null;
    Channel chan = null;

    if (targetAddress != null) {
        amqpOut = new AMQPTransportInfo(targetAddress);
        // do we have a definition for a connection factory to use for this
        // address?
        conFac = getAMQPConnectionFactory(amqpOut);

        try {
            if (conFac != null) {

                con = conFac.getConnection();
                chan = con.createChannel();
                messageSender = new AMQPMessageSender(chan, DestinationFactory.parseAddress(targetAddress));

            } else {
                messageSender = amqpOut.createAMQPSender();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else if (outTransportInfo != null && outTransportInfo instanceof AMQPTransportInfo) {

        amqpOut = (AMQPTransportInfo) outTransportInfo;
        try {
            messageSender = amqpOut.createAMQPSender();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // The message property to be used to send the content type is
    // determined by the out transport info, i.e. either from the EPR if we are sending a
    // request, or, if we are sending a response, from the configuration of the
    // service that received the request). The property name can be overridden by a
    // message context property.
    String contentTypeProperty = (String) msgCtx.getProperty(AMQPConstants.CONTENT_TYPE_PROPERTY_PARAM);
    if (contentTypeProperty == null) {
        contentTypeProperty = amqpOut.getContentTypeProperty();
    }

    try {
        sendOverAMQP(msgCtx, messageSender, contentTypeProperty, chan, amqpOut);
    } finally {
        try {
            chan.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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
 *///  w ww .  j a  va  2s.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.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testReadQueue() throws Exception {
    final int maxNumRecords = 10;
    PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port)
            .withQueue("READ").withMaxNumRecords(maxNumRecords));
    PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings())
            .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8)));

    List<String> records = generateRecords(maxNumRecords).stream()
            .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList());
    PAssert.that(output).containsInAnyOrder(records);

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {/*  ww  w.  ja v  a 2 s. co  m*/
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("READ", false, false, false, null);
        for (String record : records) {
            channel.basicPublish("", "READ", null, record.getBytes(StandardCharsets.UTF_8));
        }

        p.run();
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test(timeout = 60 * 1000)
public void testReadExchange() throws Exception {
    final int maxNumRecords = 10;
    PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port)
            .withExchange("READEXCHANGE", "fanout", "test").withMaxNumRecords(maxNumRecords));
    PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings())
            .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8)));

    List<String> records = generateRecords(maxNumRecords).stream()
            .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList());
    PAssert.that(output).containsInAnyOrder(records);

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {//  w ww . ja  va2  s. c o  m
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare("READEXCHANGE", "fanout");
        Channel finalChannel = channel;
        Thread publisher = new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
            for (int i = 0; i < maxNumRecords; i++) {
                try {
                    finalChannel.basicPublish("READEXCHANGE", "test", null,
                            ("Test " + i).getBytes(StandardCharsets.UTF_8));
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        });
        publisher.start();
        p.run();
        publisher.join();
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testWriteQueue() throws Exception {
    final int maxNumRecords = 1000;
    List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream()
            .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList());
    p.apply(Create.of(data))/*from  w w w . j  a  va 2  s . c  o  m*/
            .apply(RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withQueue("TEST"));

    final List<String> received = new ArrayList<>();
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("TEST", true, false, false, null);
        Consumer consumer = new TestConsumer(channel, received);
        channel.basicConsume("TEST", true, consumer);

        p.run();

        while (received.size() < maxNumRecords) {
            Thread.sleep(500);
        }

        assertEquals(maxNumRecords, received.size());
        for (int i = 0; i < maxNumRecords; i++) {
            assertTrue(received.contains("Test " + i));
        }
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testWriteExchange() throws Exception {
    final int maxNumRecords = 1000;
    List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream()
            .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList());
    p.apply(Create.of(data)).apply(//ww w .ja  v  a 2s  .  c  o  m
            RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withExchange("WRITE", "fanout"));

    final List<String> received = new ArrayList<>();
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare("WRITE", "fanout");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, "WRITE", "");
        Consumer consumer = new TestConsumer(channel, received);
        channel.basicConsume(queueName, true, consumer);

        p.run();

        while (received.size() < maxNumRecords) {
            Thread.sleep(500);
        }

        assertEquals(maxNumRecords, received.size());
        for (int i = 0; i < maxNumRecords; i++) {
            assertTrue(received.contains("Test " + i));
        }
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java

License:Apache License

@Override
public void publish(Event event) throws EventBusException {

    String routingKey = createRoutingKey(event);
    String eventDescription = event.getDescription();

    try {/*  w  w w.  j  a va 2 s . com*/
        Connection connection = getConnection();
        Channel channel = createChannel(connection);
        createExchange(channel, amqpExchangeName);
        publishEventToExchange(channel, amqpExchangeName, routingKey, eventDescription);
        channel.close();
    } catch (AlreadyClosedException e) {
        closeConnection();
        throw new EventBusException(
                "Failed to publish event to message broker as connection to AMQP broker in lost");
    } catch (Exception e) {
        throw new EventBusException("Failed to publish event to message broker due to " + e.getMessage());
    }
}

From source file:org.apache.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(final InputRowParser<ByteBuffer> firehoseParser, File temporaryDirectory)
        throws IOException {
    ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory);
    Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries())
            .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds()))
            .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds())));

    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = Connections.create(lyraOptions, lyraConfig);

    connection.addShutdownListener(new ShutdownListener() {
        @Override/*w  ww  . java 2  s. c  om*/
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest row as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private InputRow nextRow;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        private Iterator<InputRow> nextIterator = Collections.emptyIterator();

        @Override
        public boolean hasMore() {
            nextRow = null;
            try {
                if (nextIterator.hasNext()) {
                    nextRow = nextIterator.next();
                    return true;
                }
                // Wait for the next delivery. This will block until something is available.
                final Delivery delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    nextIterator = firehoseParser.parseBatch(ByteBuffer.wrap(delivery.getBody())).iterator();
                    if (nextIterator.hasNext()) {
                        nextRow = nextIterator.next();
                        // If delivery is non-null, we report that there is something more to process.
                        return true;
                    }
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Nullable
        @Override
        public InputRow nextRow() {
            if (nextRow == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return nextRow;
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:org.apache.flume.amqp.AmqpConsumer.java

License:Apache License

private void closeChannelSilently(Channel channel) {
    if (channel != null) {
        try {//from   www .  j av  a  2 s  .  co m
            LOG.info("Closing channel to {} ...", connectionFactory.getHost());
            channel.close();
            LOG.info("Channel to {} closed", connectionFactory.getHost());
        } catch (AlreadyClosedException e) {
            // we catch this specifically so we don't pollute the logs with already closed exceptions

        } catch (Exception e) {
            LOG.warn("Problem closing down channel", e);
        }
    }
}