Example usage for com.rabbitmq.client Channel queueBind

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

Introduction

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

Prototype

Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;

Source Link

Document

Bind a queue to an exchange, with no extra arguments.

Usage

From source file:OnlyPackege.TheMightyBank.java

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

    JSONParser jsonParster = new JSONParser();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel recvChannel = connection.createChannel();

    recvChannel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String queueName = recvChannel.queueDeclare().getQueue();
    recvChannel.queueBind(queueName, EXCHANGE_NAME, "");

    QueueingConsumer consumer = new QueueingConsumer(recvChannel);
    recvChannel.basicConsume(queueName, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String responseQueue = delivery.getProperties().getReplyTo();

        Channel sendChannel = connection.createChannel();
        sendChannel.queueDeclare(responseQueue, false, false, false, null);

        String message = new String(delivery.getBody());
        JSONObject recvObj = (JSONObject) jsonParster.parse(message);

        //to be deleted after testing
        System.out.println(" [x] Received '" + message + "'");

        JSONObject obj = new JSONObject();
        obj.put("ssn", recvObj.get("ssn"));
        obj.put("interestRate", Math.random() * 10);

        sendChannel.basicPublish("", responseQueue, null, obj.toJSONString().getBytes());
    }//from  w  ww  .j a v a 2s  .  com
}

From source file:org.apache.airavata.datacat.agent.messageBroker.AiravataUpdateListener.java

License:Apache License

public void startBroker() {
    (new Thread(new Runnable() {
        @Override//from  www  .  j a  va  2  s  . c o  m
        public void run() {
            try {
                ConnectionFactory factory = new ConnectionFactory();
                factory.setHost(RABBITMQ_HOST);

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

                channel.exchangeDeclare(EXCHANGE_NAME, "topic");
                String queueName = channel.queueDeclare().getQueue();

                channel.basicQos(1);
                channel.queueBind(queueName, EXCHANGE_NAME, BINDING_KEY);

                logger.debug("Waiting for messages. To exit press CTRL+C");

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

                while (runFileUpdateListener) {
                    QueueingConsumer.Delivery delivery = consumer.nextDelivery();

                    Message message = new Message();
                    ThriftUtils.createThriftFromBytes(delivery.getBody(), message);
                    TBase event = null;

                    if (message.getMessageType().equals(MessageType.EXPERIMENT_OUTPUT)) {

                        ExperimentOutputCreatedEvent experimentOutputCreatedEvent = new ExperimentOutputCreatedEvent();
                        ThriftUtils.createThriftFromBytes(message.getEvent(), experimentOutputCreatedEvent);

                        logger.debug(" Message Received with message id '" + message.getMessageId()
                                + "' and with message type '" + message.getMessageType()
                                + "'  with experiment name "
                                + experimentOutputCreatedEvent.getExperimentName());

                        event = experimentOutputCreatedEvent;

                        logger.debug(" [x] Received FileInfo Message'");
                        process(experimentOutputCreatedEvent, message.getUpdatedTime());
                        logger.debug(" [x] Done Processing FileInfo Message");
                    } else {
                        logger.debug("Recieved message of type ..." + message.getMessageType());
                    }
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }

    })).start();

}

From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.AMQPMonitor.java

License:Apache License

@Override
public boolean registerListener(MonitorID monitorID) throws AiravataMonitorException {
    // we subscribe to read user-host based subscription
    HostDescription host = monitorID.getHost();
    String hostAddress = host.getType().getHostAddress();
    // in amqp case there are no multiple jobs per each host, because once a job is put in to the queue it
    // will be picked by the Monitor, so jobs will not stay in this queueu but jobs will stay in finishQueue
    String channelID = CommonUtils.getChannelID(monitorID);
    if (availableChannels.get(channelID) == null) {
        try {//w  w w  .  j a  va  2s . c o  m
            //todo need to fix this rather getting it from a file
            Connection connection = AMQPConnectionUtil.connect(amqpHosts, connectionName, proxyPath);
            Channel channel = null;
            channel = connection.createChannel();
            availableChannels.put(channelID, channel);
            String queueName = channel.queueDeclare().getQueue();

            BasicConsumer consumer = new BasicConsumer(new JSONMessageParser(), localPublisher); // here we use local publisher
            channel.basicConsume(queueName, true, consumer);
            String filterString = CommonUtils.getRoutingKey(monitorID.getUserName(), hostAddress);
            // here we queuebind to a particular user in a particular machine
            channel.queueBind(queueName, "glue2.computing_activity", filterString);
            logger.info("Using filtering string to monitor: " + filterString);
        } catch (IOException e) {
            logger.error("Error creating the connection to finishQueue the job:" + monitorID.getUserName());
        }
    }
    return true;
}

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

License:Apache License

public void Subscribe() throws AMQPException {
    if (callback != null) {
        try {//  ww  w  . j a v a  2 s . co  m
            Connection connection = connectionFactory.newConnection();

            Channel channel = connection.createChannel();
            channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_FANOUT, AMQPUtil.EXCHANGE_TYPE_FANOUT);

            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, AMQPUtil.EXCHANGE_NAME_FANOUT, "");

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

            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                String message = new String(delivery.getBody());

                callback.onMessage(message);
            }
        } catch (Exception e) {
            throw new AMQPException(e);
        }
    }
}

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

License:Apache License

public void Subscribe(AMQPRoutingKey key) throws AMQPException {
    if (callback != null) {
        try {//from w  w w .  j  a va 2s.  com
            Connection connection = connectionFactory.newConnection();

            Channel channel = connection.createChannel();
            channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_DIRECT, AMQPUtil.EXCHANGE_TYPE_DIRECT);

            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, AMQPUtil.EXCHANGE_NAME_DIRECT, key.getNativeKey());

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

            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                String message = new String(delivery.getBody());

                callback.onMessage(message);
            }
        } catch (Exception e) {
            throw new AMQPException(e);
        }
    }
}

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

License:Apache License

public void Subscribe(AMQPRoutingKey topic) throws AMQPException {
    if (callback != null) {
        try {/*from ww  w.  j  ava 2 s. com*/
            Connection connection = connectionFactory.newConnection();

            Channel channel = connection.createChannel();
            channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_TOPIC, AMQPUtil.EXCHANGE_TYPE_TOPIC);

            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, AMQPUtil.EXCHANGE_NAME_TOPIC, topic.getNativeKey());

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

            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                String message = new String(delivery.getBody());

                callback.onMessage(message);
            }
        } catch (Exception e) {
            throw new AMQPException(e);
        }
    }
}

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  w w w  . j av a  2 s  .co  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 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(/* w w  w .  j a va  2 s  . 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.camel.component.rabbitmq.RabbitMQProducerIntTest.java

License:Apache License

@Test
public void producedMessageIsReceived() throws InterruptedException, IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5672);//from w  w  w  . ja v  a2 s.c o m
    factory.setUsername("cameltest");
    factory.setPassword("cameltest");
    factory.setVirtualHost("/");
    Connection conn = factory.newConnection();

    final List<Envelope> received = new ArrayList<Envelope>();

    Channel channel = conn.createChannel();
    channel.queueDeclare("sammyq", false, false, true, null);
    channel.queueBind("sammyq", EXCHANGE, "route1");
    channel.basicConsume("sammyq", true, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            received.add(envelope);
        }
    });

    template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1");
    Thread.sleep(500);
    assertEquals(1, received.size());
}

From source file:org.apache.camel.component.rabbitmq.reply.TemporaryQueueReplyManager.java

License:Apache License

@Override
protected Connection createListenerContainer() throws Exception {

    log.debug("Creating connection");
    Connection conn = endpoint.connect(executorService);

    log.debug("Creating channel");
    Channel channel = conn.createChannel();
    // setup the basicQos
    if (endpoint.isPrefetchEnabled()) {
        channel.basicQos(endpoint.getPrefetchSize(), endpoint.getPrefetchCount(), endpoint.isPrefetchGlobal());
    }/*ww w  . j  a  va  2s  .c  o m*/

    //Let the server pick a random name for us
    DeclareOk result = channel.queueDeclare();
    log.debug("Temporary queue name {}", result.getQueue());
    setReplyTo(result.getQueue());

    //TODO check for the RabbitMQConstants.EXCHANGE_NAME header 
    channel.queueBind(getReplyTo(), endpoint.getExchangeName(), getReplyTo());

    consumer = new RabbitConsumer(this, channel);
    consumer.start();

    return conn;
}