Example usage for org.springframework.amqp.rabbit.core ChannelCallback ChannelCallback

List of usage examples for org.springframework.amqp.rabbit.core ChannelCallback ChannelCallback

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.core ChannelCallback ChannelCallback.

Prototype

ChannelCallback

Source Link

Usage

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderCleanerTests.java

@Test
public void testCleanStream() {
    final RabbitBindingCleaner cleaner = new RabbitBindingCleaner();
    final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest",
            "guest");
    final String stream1 = UUID.randomUUID().toString();
    String stream2 = stream1 + "-1";
    String firstQueue = null;//  ww  w. j a  v a2  s .  c  o m
    CachingConnectionFactory connectionFactory = rabbitWithMgmtEnabled.getResource();
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    for (int i = 0; i < 5; i++) {
        String queue1Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + i);
        String queue2Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".default." + i);
        if (firstQueue == null) {
            firstQueue = queue1Name;
        }
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}")
                .buildAndExpand("/", AbstractBinder.constructDLQName(queue1Name)).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        TopicExchange exchange = new TopicExchange(queue1Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue1Name)).to(exchange).with(queue1Name));
        exchange = new TopicExchange(queue2Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue2Name)).to(exchange).with(queue2Name));
    }
    final TopicExchange topic1 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic1).with("#"));
    String foreignQueue = UUID.randomUUID().toString();
    rabbitAdmin.declareQueue(new Queue(foreignQueue));
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(foreignQueue)).to(topic1).with("#"));
    final TopicExchange topic2 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic2);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic2).with("#"));
    new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() {

        @Override
        public Void doInRabbit(Channel channel) throws Exception {
            String queueName = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + 4);
            String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));
            try {
                waitForConsumerStateNot(queueName, 0);
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Queue " + queueName + " is in use");
            }
            channel.basicCancel(consumerTag);
            waitForConsumerStateNot(queueName, 1);
            try {
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Cannot delete exchange ");
                assertThat(e).hasMessageContaining("; it has bindings:");
            }
            return null;
        }

        private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException {
            int n = 0;
            URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                    .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri();
            while (n++ < 100) {
                @SuppressWarnings("unchecked")
                Map<String, Object> queueInfo = template.getForObject(uri, Map.class);
                if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) {
                    break;
                }
                Thread.sleep(100);
            }
            assertThat(n < 100).withFailMessage("Consumer state remained at " + state + " after 10 seconds");
        }

    });
    rabbitAdmin.deleteExchange(topic1.getName()); // easier than deleting the binding
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.deleteQueue(foreignQueue);
    connectionFactory.destroy();
    Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false);
    assertThat(cleanedMap).hasSize(2);
    List<String> cleanedQueues = cleanedMap.get("queues");
    // should *not* clean stream2
    assertThat(cleanedQueues).hasSize(10);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i * 2)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i);
        assertThat(cleanedQueues.get(i * 2 + 1)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i + ".dlq");
    }
    List<String> cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);

    // wild card *should* clean stream2
    cleanedMap = cleaner.clean(stream1 + "*", false);
    assertThat(cleanedMap).hasSize(2);
    cleanedQueues = cleanedMap.get("queues");
    assertThat(cleanedQueues).hasSize(5);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i)).isEqualTo(BINDER_PREFIX + stream2 + ".default." + i);
    }
    cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

public void send(final String exchange, final String routingKey, final Message message,
        final CorrelationData correlationData) throws AmqpException {
    execute(new ChannelCallback<Object>() {

        @Override//from  w  ww  .  j  ava  2  s .  co m
        public Object doInRabbit(Channel channel) throws Exception {
            doSend(channel, exchange, routingKey, message, correlationData);
            return null;
        }
    });
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

@Override
public Message receive(final String queueName) {
    return execute(new ChannelCallback<Message>() {

        @Override//from ww  w .  j  av a2 s.  c  o  m
        public Message doInRabbit(Channel channel) throws IOException {
            GetResponse response = channel.basicGet(queueName, !isChannelTransacted());
            // Response can be null is the case that there is no message on
            // the queue.
            if (response != null) {
                long deliveryTag = response.getEnvelope().getDeliveryTag();
                if (isChannelLocallyTransacted(channel)) {
                    channel.basicAck(deliveryTag, false);
                    channel.txCommit();
                } else if (isChannelTransacted()) {
                    // Not locally transacted but it is transacted so it
                    // could be synchronized with an external transaction
                    ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag);
                }

                return RabbitTemplate.this.buildMessageFromResponse(response);
            }
            return null;
        }
    });
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

@SuppressWarnings("unchecked")
private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback,
        final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException {
    return this.execute(new ChannelCallback<Boolean>() {

        @Override/*from w  w  w  .  j  a  va  2  s .  c om*/
        public Boolean doInRabbit(Channel channel) throws Exception {
            boolean channelTransacted = RabbitTemplate.this.isChannelTransacted();

            GetResponse response = channel.basicGet(queueName, !channelTransacted);
            // Response can be null in the case that there is no message on
            // the queue.
            if (response != null) {
                long deliveryTag = response.getEnvelope().getDeliveryTag();
                boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel);

                if (channelLocallyTransacted) {
                    channel.basicAck(deliveryTag, false);
                } else if (channelTransacted) {
                    // Not locally transacted but it is transacted so it
                    // could be synchronized with an external transaction
                    ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(),
                            channel, deliveryTag);
                }

                Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response);

                Object receive = receiveMessage;
                if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) {
                    receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage);
                }

                S reply;
                try {
                    reply = callback.handle((R) receive);
                } catch (ClassCastException e) {
                    StackTraceElement[] trace = e.getStackTrace();
                    if (trace[0].getMethodName().equals("handle")
                            && trace[1].getFileName().equals("RabbitTemplate.java")) {
                        throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback
                                + "' can't handle received object '" + receive + "'", e);
                    } else {
                        throw e;
                    }
                }

                if (reply != null) {
                    Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply);

                    Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply);

                    MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties();
                    MessageProperties replyMessageProperties = replyMessage.getMessageProperties();

                    Object correlation = RabbitTemplate.this.correlationKey == null
                            ? receiveMessageProperties.getCorrelationId()
                            : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey);

                    if (RabbitTemplate.this.correlationKey == null || correlation == null) {
                        // using standard correlationId property
                        if (correlation == null) {
                            String messageId = receiveMessageProperties.getMessageId();
                            if (messageId != null) {
                                correlation = messageId.getBytes(RabbitTemplate.this.encoding);
                            }
                        }
                        replyMessageProperties.setCorrelationId((byte[]) correlation);
                    } else {
                        replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation);
                    }

                    // 'doSend()' takes care about 'channel.txCommit()'.
                    RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(),
                            replyMessage, null);
                } else if (channelLocallyTransacted) {
                    channel.txCommit();
                }

                return true;
            }
            return false;
        }
    });
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

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

        @Override//  ww  w . j a va2s.  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:org.kurento.rabbitmq.RabbitTemplate.java

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

        @Override/*from  w w  w. j a  v  a2  s.  c om*/
        public Message doInRabbit(Channel channel) throws Exception {
            final PendingReply pendingReply = new PendingReply();

            byte[] messageTagBytes = message.getMessageProperties().getCorrelationId();

            String messageTag;
            if (messageTagBytes != null) {
                messageTag = new String(messageTagBytes);
            } else {
                messageTag = UUID.randomUUID().toString();
            }

            RabbitTemplate.this.replyHolder.put(messageTag, pendingReply);
            // Save any existing replyTo and correlation data
            String savedReplyTo = message.getMessageProperties().getReplyTo();
            pendingReply.setSavedReplyTo(savedReplyTo);
            if (StringUtils.hasLength(savedReplyTo) && logger.isDebugEnabled()) {
                logger.debug("Replacing replyTo header:" + savedReplyTo
                        + " in favor of template's configured reply-queue:"
                        + RabbitTemplate.this.replyQueue.getName());
            }
            message.getMessageProperties().setReplyTo(RabbitTemplate.this.replyQueue.getName());
            String savedCorrelation = null;
            if (RabbitTemplate.this.correlationKey == null) { // using
                // standard
                // correlationId
                // property
                byte[] correlationId = message.getMessageProperties().getCorrelationId();
                if (correlationId != null) {
                    savedCorrelation = new String(correlationId, RabbitTemplate.this.encoding);
                }
            } else {
                savedCorrelation = (String) message.getMessageProperties().getHeaders()
                        .get(RabbitTemplate.this.correlationKey);
            }
            pendingReply.setSavedCorrelation(savedCorrelation);
            if (RabbitTemplate.this.correlationKey == null) { // using
                // standard
                // correlationId
                // property
                message.getMessageProperties()
                        .setCorrelationId(messageTag.getBytes(RabbitTemplate.this.encoding));
            } else {
                message.getMessageProperties().setHeader(RabbitTemplate.this.correlationKey, messageTag);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Sending message with tag " + messageTag);
            }
            doSend(channel, exchange, routingKey, message, null);
            LinkedBlockingQueue<Message> replyHandoff = pendingReply.getQueue();
            Message reply = (replyTimeout < 0) ? replyHandoff.take()
                    : replyHandoff.poll(replyTimeout, TimeUnit.MILLISECONDS);
            RabbitTemplate.this.replyHolder.remove(messageTag);
            return reply;
        }
    });
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdmin.java

public void declareExchange(final Exchange exchange) {
    this.rabbitTemplate.execute(new ChannelCallback<Object>() {
        public Object doInRabbit(Channel channel) throws Exception {
            declareExchanges(channel, exchange);
            return null;
        }/*from  w  w  w. j  av  a2 s  .c  o  m*/
    });
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdmin.java

@ManagedOperation
public boolean deleteExchange(final String exchangeName) {
    return this.rabbitTemplate.execute(new ChannelCallback<Boolean>() {
        public Boolean doInRabbit(Channel channel) throws Exception {
            if (isDeletingDefaultExchange(exchangeName)) {
                return true;
            }/* ww  w  .  j a  v  a 2s .  c om*/

            try {
                channel.exchangeDelete(exchangeName);
            } catch (IOException e) {
                return false;
            }
            return true;
        }
    });
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdmin.java

@ManagedOperation
public void declareQueue(final Queue queue) {
    this.rabbitTemplate.execute(new ChannelCallback<Object>() {
        public Object doInRabbit(Channel channel) throws Exception {
            declareQueues(channel, queue);
            return null;
        }//from  w  w w. j a  va 2s.  c  o  m
    });
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdmin.java

/**
 * Declares a server-named exclusive, autodelete, non-durable queue.
 */// ww w  .ja  va2  s . c  o m
@ManagedOperation
public Queue declareQueue() {
    DeclareOk declareOk = this.rabbitTemplate.execute(new ChannelCallback<DeclareOk>() {
        public DeclareOk doInRabbit(Channel channel) throws Exception {
            return channel.queueDeclare();
        }
    });
    Queue queue = new Queue(declareOk.getQueue(), false, true, true);
    return queue;
}