Example usage for com.rabbitmq.client Channel exchangeDeclarePassive

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

Introduction

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

Prototype

Exchange.DeclareOk exchangeDeclarePassive(String name) throws IOException;

Source Link

Document

Declare an exchange passively; that is, check if the named exchange exists.

Usage

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

License:Apache License

public void checkExchangeOrDie(String exchangeName) throws UnreachableModuleException {
    if (!connection.isOpen()) {
        throw new UnreachableModuleException("Not connected to broker!");
    }//from  w w  w .  j  ava2  s  . c o  m
    try {
        Channel ch = connection.createChannel();
        AMQP.Exchange.DeclareOk declare = ch.exchangeDeclarePassive(exchangeName);
        ch.close();
    } catch (Exception e) {
        throw new UnreachableModuleException("Queue not exists!");
    }
}

From source file:com.DeadLetterSender.java

License:Open Source License

public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);//from   ww  w.  j  a va 2s .co  m
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    // Request Message
    String message = "<soapenv:Envelope" + " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "<soapenv:Body>\n" + "  <p:greet xmlns:p=\"http://service.wso2.org\">\n" + "     <in>" + "IBM"
            + "</in>\n" + "  </p:greet>\n" + "</soapenv:Body>\n" + "</soapenv:Envelope>";

    // Adding Message Properties
    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
    builder.messageId("007");
    builder.contentType("text/xml");
    builder.correlationId("1111");
    builder.replyTo(REPLY_QUEUE_NAME);
    builder.contentEncoding("UTF-8");

    // Custom user properties
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("SOAP_ACTION", "getQuote");
    builder.headers(headers);

    // Publish the message to exchange
    channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, builder.build(), message.getBytes());
    channel.close();
    connection.close();
}

From source file:com.ericsson.eiffel.remrem.publish.helper.RabbitMqProperties.java

License:Apache License

/**
 * This method is used to check exchange exists or not
 * @return Boolean/*from  www.ja v  a  2  s . co  m*/
 * @throws RemRemPublishException
 * @throws TimeoutException
 * @throws IOException
 */
private boolean hasExchange() throws RemRemPublishException {
    log.info("Exchange is: " + exchangeName);
    Connection connection;
    try {
        connection = factory.newConnection();
    } catch (final IOException | TimeoutException e) {
        throw new RemRemPublishException("Exception occurred while creating Rabbitmq connection ::"
                + factory.getHost() + factory.getPort() + e.getMessage());
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (final IOException e) {
        log.info("Exchange " + exchangeName + " does not Exist");
        throw new RemRemPublishException("Exception occurred while creating Channel with Rabbitmq connection ::"
                + factory.getHost() + factory.getPort() + e.getMessage());
    }
    try {
        channel.exchangeDeclarePassive(exchangeName);
        return true;
    } catch (final IOException e) {
        log.info("Exchange " + exchangeName + " does not Exist");
        return false;
    } finally {
        if (channel != null && channel.isOpen()) {
            try {
                channel.close();
                connection.close();
            } catch (IOException | TimeoutException e) {
                log.warn("Exception occurred while closing the channel" + e.getMessage());
            }
        }
    }
}

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 {//ww  w.j  ava  2s .  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 {//from  w ww  . java  2  s  .c o  m
        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:it.txt.ens.authorisationService.amqp.AMQPExchangeHelper.java

License:Apache License

/**
 * Checks the existence of an exchange /*from  w ww.  ja va 2  s  .com*/
 * 
 * @param channel
 * @param exchange
 * @return
 */
public boolean exists(Channel channel, String exchange) {
    try {
        channel.exchangeDeclarePassive(exchange);
        return true;
    } catch (IOException e) {
        return false;
    } finally {
    }
}

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 w w.j  a  v a2 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.james.transport.mailets.AmqpForwardAttribute.java

License:Apache License

private void sendContent(Map<String, byte[]> content) throws IOException, TimeoutException {
    Connection connection = null;
    Channel channel = null;
    try {// www.j  a  va 2 s .  com
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclarePassive(exchange);
        sendContentOnChannel(channel, content);
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore.java

License:Open Source License

/**
 * Create a Queue to store messages, this will used queueName parameter
 *
 * @throws IOException : if its enable to create the queue or exchange
 */// w  w w.  j av  a  2 s  .  c o m
private void setQueue() throws IOException {
    Channel channel = null;
    try {
        channel = producerConnection.createChannel();
        try {
            channel.queueDeclarePassive(queueName);
        } catch (java.io.IOException e) {
            logger.info("Queue :" + queueName + " not found.Declaring queue.");
            if (!channel.isOpen()) {
                channel = producerConnection.createChannel();
            }
            //Hashmap with names and parameters can be used in the place of null argument
            //Eg: adding dead letter exchange to the queue
            //params: (queueName, durable, exclusive, autoDelete, paramMap)
            channel.queueDeclare(queueName, true, false, false, null);
        }
        //declaring exchange
        if (exchangeName != null) {
            try {
                channel.exchangeDeclarePassive(exchangeName);
            } catch (java.io.IOException e) {
                logger.info("Exchange :" + exchangeName + " not found. Declaring exchange.");
                if (!channel.isOpen()) {
                    channel = producerConnection.createChannel();
                }
                //params : ( exchangeName, exchangeType, durable, autoDelete, paramMap )
                channel.exchangeDeclare(exchangeName, "direct", true, false, null);
            }
            channel.queueBind(queueName, exchangeName, routeKey);
        }
    } finally {
        channel.close();
    }
}

From source file:org.mule.transport.amqp.AmqpEndpointUtil.java

License:Open Source License

public static String getOrCreateExchange(final Channel channel, final ImmutableEndpoint endpoint,
        final boolean activeDeclarationsOnly) throws IOException {
    final String outboundEndpointAddress = endpoint.getAddress();
    final String exchangeName = getExchangeName(outboundEndpointAddress);

    if (StringUtils.isBlank(exchangeName)) {
        LOG.info("Using default exchange for endpoint: " + endpoint);
        return exchangeName;
    }/*  w w w. j a va 2s.co  m*/

    final String exchangeType = (String) endpoint.getProperty(EXCHANGE_TYPE);
    if (StringUtils.isNotBlank(exchangeType)) {
        // an exchange type is provided -> the exchange must be declared
        final boolean exchangeDurable = BooleanUtils.toBoolean((String) endpoint.getProperty(EXCHANGE_DURABLE));
        final boolean exchangeAutoDelete = BooleanUtils
                .toBoolean((String) endpoint.getProperty(EXCHANGE_AUTO_DELETE));

        channel.exchangeDeclare(exchangeName, exchangeType, exchangeDurable, exchangeAutoDelete, NO_ARGS);

        LOG.info("Declared exchange: " + exchangeName + " of type: " + exchangeType + ", durable: "
                + exchangeDurable + ", autoDelete: " + exchangeAutoDelete);
    } else if (!activeDeclarationsOnly) {
        // no exchange type -> ensure the exchange exists
        channel.exchangeDeclarePassive(exchangeName);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Validated presence of exchange: " + exchangeName);
        }
    }

    return exchangeName;
}