Example usage for com.rabbitmq.client Channel queueDeclare

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

Introduction

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

Prototype

Queue.DeclareOk queueDeclare() throws IOException;

Source Link

Document

Actively declare a server-named exclusive, autodelete, non-durable queue.

Usage

From source file:com.jbrisbin.vcloud.classloader.RabbitMQResourceProvider.java

License:Apache License

protected void declareResources() throws IOException {
    Channel mq = getChannel();
    synchronized (mq) {
        mq.exchangeDeclare(exchange, "topic", true, false, null);
        if (null == this.queue) {
            queue = mq.queueDeclare().getQueue();
        } else {//  www. j a  va  2s.  c  o m
            mq.queueDeclare(this.queue, true, false, true, null);
        }
        mq.queueBind(queue, exchange, routingKey);
    }
}

From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java

License:Apache License

protected Message doSendAndReceiveWithTemporary(final String exchange, final String routingKey,
        final Message message) {
    return this.execute(new ChannelCallback<Message>() {

        @Override//from   ww  w . j a  v  a  2 s  . co  m
        public Message doInRabbit(Channel channel) throws Exception {
            final ArrayBlockingQueue<Message> replyHandoff = new ArrayBlockingQueue<Message>(1);

            Assert.isNull(message.getMessageProperties().getReplyTo(),
                    "Send-and-receive methods can only be used if the Message does not already have a replyTo property.");
            DeclareOk queueDeclaration = channel.queueDeclare();
            String replyTo = queueDeclaration.getQueue();
            message.getMessageProperties().setReplyTo(replyTo);

            String consumerTag = UUID.randomUUID().toString();
            DefaultConsumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    MessageProperties messageProperties = messagePropertiesConverter
                            .toMessageProperties(properties, envelope, encoding);
                    Message reply = new Message(body, messageProperties);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Message received " + reply);
                    }
                    try {
                        replyHandoff.put(reply);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            };
            channel.basicConsume(replyTo, true, consumerTag, true, true, null, consumer);
            doSend(channel, exchange, routingKey, message, null);
            Message reply = (replyTimeout < 0) ? replyHandoff.take()
                    : replyHandoff.poll(replyTimeout, TimeUnit.MILLISECONDS);
            channel.basicCancel(consumerTag);
            return reply;
        }
    });
}

From source file:com.mycompany.javateste.queues.pubsub.ReceiveLogs.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override/*from  www  . j av a  2s.  c  o m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:com.mycompany.javateste.queues.routing.ReceiveLogsDirect.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    if (argv.length < 1) {
        System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
        System.exit(1);/*from w ww  .ja v  a 2  s. com*/
    }

    for (String severity : argv) {
        channel.queueBind(queueName, EXCHANGE_NAME, severity);
    }
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:com.mycompany.javateste.queues.topic.ReceiveLogsTopic.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    if (argv.length < 1) {
        System.err.println("Usage: ReceiveLogsTopic [binding_key]...");
        System.exit(1);//from w  w w.  j  av  a 2 s.  c om
    }

    for (String bindingKey : argv) {
        channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
    }

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:com.nesscomputing.amqp.ExchangeConsumer.java

License:Apache License

@Override
protected void connectCallback(@Nonnull final Channel channel) throws IOException {
    super.connectCallback(channel);

    if (getConfig().isDeclaring()) {
        channel.exchangeDeclare(getName(), getConfig().getExchangeType(), getConfig().isDurable(),
                getConfig().isAutoDelete(), null);
    }// ww w  . j ava  2s .  com
    final String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, getName(), routingKey);

    channel.basicConsume(queueName, false, getConsumer());
}

From source file:com.opengamma.transport.amqp.AmqpByteArrayRequestSender.java

License:Open Source License

/**
 * Creates an instance./*from w  w  w .  j ava2s .  com*/
 * 
 * @param connectionFactory  the connection factory, not null
 * @param timeout  the timeout, positive
 * @param executor  the executor, not null
 * @param exchange  the exchange, not null
 * @param routingKey  the routing key, not null
 */
public AmqpByteArrayRequestSender(ConnectionFactory connectionFactory, long timeout,
        ScheduledExecutorService executor, String exchange, String routingKey) {
    super(new RabbitTemplate(connectionFactory), exchange, routingKey);
    ArgumentChecker.notNull(connectionFactory, "connectionFactory");
    ArgumentChecker.notNull(executor, "executor");

    if (timeout <= 0) {
        throw new IllegalArgumentException("Timeout must be positive");
    }
    _timeout = timeout;
    _executor = executor;

    try {
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);

        Queue.DeclareOk declareResult = channel.queueDeclare();
        _replyToQueue = declareResult.getQueue();

        channel.queueBind(_replyToQueue, getExchange(), _replyToQueue);
        connection.close();

    } catch (IOException e) {
        throw new RuntimeException("Failed to create reply to queue", e);
    }

    _container = new SimpleMessageListenerContainer();
    _container.setConnectionFactory(connectionFactory);
    _container.setQueueNames(_replyToQueue);
    _container.setMessageListener(this);
}

From source file:com.vmware.vhadoop.vhm.rabbit.RabbitConnection.java

License:Open Source License

private synchronized String getQueueName() throws IOException {
    if (_queueName == null) {
        String exchangeName = _credentials.getExchangeName();
        Channel channel = getChannel();
        channel.exchangeDeclare(exchangeName, "direct", true, false, null); /* TODO: Externalize? */
        _queueName = channel.queueDeclare().getQueue();
        channel.queueBind(_queueName, exchangeName, _credentials.getRouteKeyCommand());
        _log.fine("Created transient queue: " + _queueName);
    }/*w ww  .  j av  a 2s  .c  o  m*/

    return _queueName;
}

From source file:controllerStuff.ControllerPublisher.java

private void attachControllerCallback(Controller controllerObject) {
    try {//from w w w . j a  v  a 2s  .  c o m

        Channel controllerCallbackChannel = connection.createChannel();
        controllerCallbackChannel.exchangeDeclare(EXCHANGE_CONTOLLER_CMD, "topic");
        String sensChName = controllerCallbackChannel.queueDeclare().getQueue();
        controllerCallbackChannel.queueBind(sensChName, EXCHANGE_CONTOLLER_CMD,
                BIND_KEY_BASE + nodeID + '.' + controllerObject.getName());

        System.out.println(BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); //Debug

        controllerCallbackChannel.basicConsume(sensChName, true,
                new DefaultConsumer(controllerCallbackChannel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope,
                            AMQP.BasicProperties properties, byte[] body) throws IOException {

                        controllerObject.call(new String(body, "UTF-8"));

                    }
                });

    } catch (IOException ex) {
        Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java

License:Apache License

/**
 * Creates an instance of {@link AMQPEndpoint} whilst
 * mocking all RabbitMQ-Classes / ifaces involved.
 * //  w ww.  j  a  v  a  2  s.c  om
 * @throws IOException
 */
@Test
public void testAMQPLifecycle() throws IOException {
    // prepare mocks
    ConnectionFactory fac = mock(ConnectionFactory.class);
    Connection con = mock(Connection.class);
    Channel chan = mock(Channel.class);
    Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class);

    // ConnectionFactory
    when(fac.newConnection()).thenReturn(con);
    // Connection
    when(con.createChannel()).thenReturn(chan);
    // Channel
    when(chan.queueDeclare()).thenReturn(declareOK);
    // DeclareOK result object
    String queueName = "testQueue";
    when(declareOK.getQueue()).thenReturn(queueName);

    AMQPEndpoint ep = new AMQPEndpoint();
    Whitebox.setInternalState(ep, "connectionFactory", fac);

    ep.configure(this.exampleConf);
    ep.start();

    // verify "important" connect methods were called
    verify(fac).newConnection();
    verify(con).createChannel();
    verify(chan).queueDeclare();
    verify(declareOK).getQueue();
    // in the example conf we're bindingn to 3 queues, let's check that
    String exchange = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_EXCHANGE_NAME);
    String routingKey = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_ROUTING_KEY);
    // listens for broadcasts
    verify(chan, times(1)).queueBind(eq(queueName), eq(exchange), eq("broadcast"));
    // listens for tasks
    verify(chan, times(1)).queueBind(eq("cit_stream_tasks_queue_" + routingKey), eq(exchange),
            eq("task." + routingKey));
    // listens for broadcasts to broadcast.test
    verify(chan, times(1)).queueBind(eq(queueName), eq(exchange), eq("broadcast." + routingKey));
    String exclusiveQueueName = Whitebox.getInternalState(ep, "exclusiveQueueName");
    assertEquals(queueName, exclusiveQueueName);
}