Example usage for com.rabbitmq.client Channel basicCancel

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

Introduction

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

Prototype

void basicCancel(String consumerTag) throws IOException;

Source Link

Document

Cancel a consumer.

Usage

From source file:com.cisco.oss.foundation.message.RabbitMQMessageConsumerWithoutTL.java

License:Apache License

@Override
public boolean unRregisterMessageHandler() {
    boolean success = false;
    if (isRegistered.compareAndSet(true, false)) {
        if (consumer != null) {
            try {
                Channel channel = consumer.getChannel();
                channel.basicCancel(this.consumerTag);
                success = true;/* ww w .  j a  va  2s  . com*/
            } catch (IOException e) {
                LOGGER.error("can't unregsiter the handler. reaon: {}", e, e);
            }
        }
    } else {
        LOGGER.warn("can't unregister as there is no handler currently registered");
    }
    return success;

}

From source file:com.flipkart.bifrost.framework.impl.RabbitMQBifrostExecutor.java

License:Apache License

@Override
public void shutdown() throws BifrostException {
    try {//from   www.  j  a va  2 s  .  co m
        publishChannel.close();
        for (ReplyListener<T> listener : listeners) {
            Channel channel = listener.getChannel();
            channel.basicCancel(listener.getConsumerTag());
            channel.close();
        }
        //TODO::Save the futures and shut them down
    } catch (Exception e) {
        logger.error("Error publishing: ", e);
    }
}

From source file:com.flipkart.bifrost.framework.impl.RabbitMQBifrostRemoteCallExecutionServer.java

License:Apache License

@Override
public void stop() throws BifrostException {
    try {//from   w  w  w.  j  av  a2 s .com
        for (RabbitMQExecutionServerListener<T> listener : listeners) {
            if (!Strings.isNullOrEmpty(listener.getConsumerTag())) {
                Channel channel = listener.getChannel();
                channel.basicCancel(listener.getConsumerTag());
                channel.close();
            }
        }
    } catch (IOException e) {
        throw new BifrostException(BifrostException.ErrorCode.IO_ERROR, "Error unregistering listener", e);
    }
}

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   w  w w. ja  va  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.nesscomputing.amqp.AbstractConsumer.java

License:Apache License

@Override
protected void disconnectCallback(@Nullable final Channel channel) {
    if (channel != null && channel.isOpen()) {
        final QueueingConsumer queueingConsumer = consumerHolder.get();

        if (queueingConsumer != null) {
            final String consumerTag = queueingConsumer.getConsumerTag();

            if (consumerTag != null) {
                try {
                    channel.basicCancel(consumerTag);
                } catch (IOException ioe) {
                    LOG.warnDebug(ioe, "While cancelling subscription for %s", consumerTag);
                }/*from   www.j  av  a  2  s .co m*/
            }
        }
    }
}

From source file:net.lshift.accent.AccentConsumer.java

License:Apache License

@Override
public void close() throws IOException {
    this.owner.removeChannelSetupListener(this);

    // Attempt to cancel once. Failures will result in the channel being recreated, so it isn't necessary to retry.
    this.owner.executeIfChannelValid(new ChannelCallback() {
        public void runWithChannel(Channel c) throws IOException {
            if (hasUnderlyingConsume) {
                c.basicCancel(consumerTag);
                hasUnderlyingConsume = false;
            }// ww  w. ja  va  2  s  . c o  m
        }
    });
}

From source file:org.apache.axis2.transport.rabbitmq.RabbitMQSender.java

License:Open Source License

private void processResponse(RabbitMQConnectionFactory factory, MessageContext msgContext, String correlationID,
        String replyTo, Hashtable<String, String> eprProperties) throws IOException {

    Connection connection = factory.createConnection();

    if (!RabbitMQUtils.isQueueAvailable(connection, replyTo)) {
        log.info("Reply-to queue : " + replyTo + " not available, hence creating a new one");
        RabbitMQUtils.declareQueue(connection, replyTo, eprProperties);
    }//from w w w .  j  a va 2  s  .  co  m

    Channel channel = connection.createChannel();
    QueueingConsumer consumer = new QueueingConsumer(channel);
    QueueingConsumer.Delivery delivery = null;
    RabbitMQMessage message = new RabbitMQMessage();
    boolean responseFound = false;

    int timeout = RabbitMQConstants.DEFAULT_REPLY_TO_TIMEOUT;
    String timeoutStr = eprProperties.get(RabbitMQConstants.REPLY_TO_TIMEOUT);
    if (!StringUtils.isEmpty(timeoutStr)) {
        try {
            timeout = Integer.parseInt(timeoutStr);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading replyto timeout value. Proceeding with default value (30000ms)",
                    e);
        }
    }

    //start consuming without acknowledging
    String consumerTag = channel.basicConsume(replyTo, false, consumer);

    try {
        while (!responseFound) {
            log.debug("Waiting for next delivery from reply to queue " + replyTo);
            delivery = consumer.nextDelivery(timeout);
            if (delivery != null) {
                if (delivery.getProperties().getCorrelationId().equals(correlationID)) {
                    responseFound = true;
                    log.debug(
                            "Found matching response with correlation ID : " + correlationID + ". Sending ack");
                    //acknowledge correct message
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } else {
                    //not acknowledge wrong messages and re-queue
                    log.debug("Found messages with wrong correlation ID. Re-queueing and sending nack");
                    channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
                }
            }
        }
    } catch (ShutdownSignalException e) {
        log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage());
    } catch (InterruptedException e) {
        log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage());
    } catch (ConsumerCancelledException e) {
        log.error("Error receiving message from RabbitMQ broker" + e.getLocalizedMessage());
    } finally {
        if (channel != null || channel.isOpen()) {
            //stop consuming
            channel.basicCancel(consumerTag);
        }
    }

    if (delivery != null) {
        log.debug("Processing response from reply-to queue");
        AMQP.BasicProperties properties = delivery.getProperties();
        Map<String, Object> headers = properties.getHeaders();
        message.setBody(delivery.getBody());
        message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag());
        message.setReplyTo(properties.getReplyTo());
        message.setMessageId(properties.getMessageId());

        //get content type from message
        String contentType = properties.getContentType();
        if (contentType == null) {
            //if not get content type from transport parameter
            contentType = eprProperties.get(RabbitMQConstants.REPLY_TO_CONTENT_TYPE);
            if (contentType == null) {
                //if none is given, set to default content type
                log.warn("Setting default content type " + RabbitMQConstants.DEFAULT_CONTENT_TYPE);
                contentType = RabbitMQConstants.DEFAULT_CONTENT_TYPE;
            }
        }
        message.setContentType(contentType);
        message.setContentEncoding(properties.getContentEncoding());
        message.setCorrelationId(properties.getCorrelationId());

        if (headers != null) {
            message.setHeaders(headers);
            if (headers.get(RabbitMQConstants.SOAP_ACTION) != null) {
                message.setSoapAction(headers.get(RabbitMQConstants.SOAP_ACTION).toString());
            }
        }

        MessageContext responseMsgCtx = createResponseMessageContext(msgContext);
        RabbitMQUtils.setSOAPEnvelope(message, responseMsgCtx, contentType);
        handleIncomingMessage(responseMsgCtx, RabbitMQUtils.getTransportHeaders(message),
                message.getSoapAction(), message.getContentType());
    }
}

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

License:Apache License

@Override
public void unsubscribe(UUID subscriberId, EventSubscriber subscriber) throws EventBusException {
    try {/*from   www.j av a2  s.  c  o  m*/
        String classname = subscriber.getClass().getName();
        String queueName = UUID.nameUUIDFromBytes(classname.getBytes()).toString();
        Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName);
        Channel channel = queueDetails.second();
        channel.basicCancel(queueName);
        _subscribers.remove(queueName, queueDetails);
    } catch (Exception e) {
        throw new EventBusException("Failed to unsubscribe from event bus due to " + e.getMessage());
    }
}

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

License:Open Source License

public AmqpMessage consume(final Channel channel, final String queue, final boolean autoAck, final long timeout)
        throws IOException, InterruptedException {
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    final String consumerTag = channel.basicConsume(queue, autoAck, consumer);
    final Delivery delivery = consumer.nextDelivery(timeout);
    channel.basicCancel(consumerTag);

    if (delivery == null)
        return null;

    return new AmqpMessage(consumerTag, delivery.getEnvelope(), delivery.getProperties(), delivery.getBody());
}

From source file:org.mule.transport.amqp.internal.client.MessageConsumer.java

License:Open Source License

public AmqpMessage consumeMessage(final Channel channel, final String queue, final boolean autoAck,
        final long timeout) throws IOException, InterruptedException {
    final long startTime = System.currentTimeMillis();

    // try first with a basic get to potentially quickly retrieve a pending message
    final GetResponse getResponse = channel.basicGet(queue, autoAck);

    // if timeout is zero or if a message has been fetched don't go any further
    if ((timeout == 0) || (getResponse != null)) {
        return getResponse == null ? null
                : new AmqpMessage(null, getResponse.getEnvelope(), getResponse.getProps(),
                        getResponse.getBody());
    }// w w  w.  ja v a 2 s  .  c  o m

    // account for the time taken to perform the basic get
    final long elapsedTime = System.currentTimeMillis() - startTime;
    final long actualTimeOut = timeout - elapsedTime;
    if (actualTimeOut < 0) {
        return null;
    }

    final QueueingConsumer consumer = new SingleMessageQueueingConsumer(channel);

    // false -> no AMQP-level autoAck with the SingleMessageQueueingConsumer
    final String consumerTag = channel.basicConsume(queue, false, consumer);
    try {
        final QueueingConsumer.Delivery delivery = consumer.nextDelivery(actualTimeOut);

        if (delivery == null) {
            return null;
        } else {
            if (autoAck) {
                // ack only if auto-ack was requested, otherwise it's up to the caller to ack
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }

            return new AmqpMessage(consumerTag, delivery.getEnvelope(), delivery.getProperties(),
                    delivery.getBody());
        }
    } finally {
        try {
            channel.basicCancel(consumerTag);
        } catch (IOException e) {
            /**
             * The broker could decide to cancel a subscription on certain situations
             */
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Subscription to channel with consumerTag "
                        + StringUtils.defaultString(consumerTag) + " could not be closed.", e);
            }
        }
    }
}