Example usage for com.rabbitmq.client Channel basicNack

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

Introduction

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

Prototype

void basicNack(long deliveryTag, boolean multiple, boolean requeue) throws IOException;

Source Link

Document

Reject one or several received messages.

Usage

From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMain.java

public static void main(String[] args) {

    //activate logging level if it is DEBUG, default is INFO so no need for any
    //action if it is otherwise
    Injector propInjector = Guice.createInjector(new GeminiPropertiesModule());
    GeminiProperties properties = propInjector.getInstance(GeminiProperties.class);
    if (properties.getProperties().getProperty("LOGGING_LEVEL").equals("DEBUG")) {
        Configurator.defaultConfig().level(Level.DEBUG).activate();
    }/*from   w ww.j a  v a  2 s . c  o  m*/

    //inject the mapper as it will be used in all the threads
    Injector mapperInjector = Guice.createInjector(new GeminiMapperModule());
    mapper = mapperInjector.getInstance(GeminiMapper.class);

    //the app.yml to deployment.yml converter
    Thread yamlConverterThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("YAML_MAPPER_TOPIC"));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: YAML Mapper - could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Fatal Error: YAML Mapper - could not retrieve message. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            Integer status = 0;
            if (routingKey.equals(properties.getProperties().getProperty("YAML_MAPPER_MAP_APP"))) {
                status = mapApptoDeployment(jsonBody);
            } else {
                continue;
            }

            if (status == 0) {
                try {
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } catch (IOException ex) {
                    Logger.error("Could not ack message. Exception: {}", ex);
                }
            } else {
                //failed so requeue the message
                try {
                    channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
                } catch (IOException ex) {
                    Logger.error("Could not nack message. Exception: {}", ex);
                }
            }
        }
    });
    yamlConverterThread.start();

    //the networking message recevier
    Thread networkingThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("NETWORK_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);

                //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_CREATE"))) {
                createNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_UPDATE"))) {
                updateNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_DELETE"))) {
                deleteNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_CREATE"))) {
                createSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_UPDATE"))) {
                updateSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_DELETE"))) {
                deleteSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_CREATE"))) {
                createRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_UPDATE"))) {
                updateRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_DELETE"))) {
                deleteRouter(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    networkingThread.start();

    //the load balancer 
    Thread lbThread = new Thread(() -> {
    });

    lbThread.start();

    //the security thread
    Thread securityThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("SECURITY_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_CREATE"))) {
                createSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_UPDATE"))) {
                updateSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_DELETE"))) {
                deleteSecurityGroup(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_CREATE"))) {
                createSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_UPDATE"))) {
                updateSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_DELETE"))) {
                deleteSecurityGroupRule(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    securityThread.start();
}

From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//from w w  w .  ja va2  s  . com
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getDlrReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());

                    //check if any parameter is empty
                    if (s.length == 2) {
                        dataToPost.put(s[0], s[1]);
                    } else {
                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]);
                        dataToPost.put(s[0], null);
                    }
                }

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    channel.basicAck(deliveryTag, false);

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//  w  w w.  j av a  2 s.  co  m
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getSmsReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                    dataToPost.put(s[0], s[1]);
                }
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    if (saveRequestData()) {

                        channel.basicAck(deliveryTag, false);
                    } else {
                        channel.basicNack(deliveryTag, false, true);
                    }

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                API_CALL_STATS.clear();
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.viadeo.kasper.core.component.event.eventbus.EventMessageHandler.java

License:Open Source License

@Override
public void onMessage(Message message, Channel channel) throws Exception {
    final long deliveryTag = message.getMessageProperties().getDeliveryTag();
    final EventMessage eventMessage;

    try {/*from w  w  w  .  j  av a 2 s.c o m*/
        eventMessage = (EventMessage) converter.fromMessage(message);
    } catch (Throwable e) {
        messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(), e));
        channel.basicNack(deliveryTag, false, false);
        return;
    }

    metricRegistry.counter(HANDLE_MESSAGE_COUNT_METRIC).inc();
    metricRegistry.histogram(HANDLE_MESSAGE_TIME_METRIC).update(timeTaken(eventMessage));

    MDC.setContextMap(Maps.transformEntries(eventMessage.getMetaData(),
            new Maps.EntryTransformer<String, Object, String>() {
                @Override
                public String transformEntry(String key, Object value) {
                    return String.valueOf(value);
                }
            }));

    EventResponse response = null;

    try {
        response = eventListener
                .handle(new com.viadeo.kasper.core.component.event.listener.EventMessage(eventMessage));
    } catch (Exception e) {
        logger.error("Can't process event", e);
        response = EventResponse.failure(new KasperReason(CoreReasonCode.INTERNAL_COMPONENT_ERROR, e));
    }

    final KasperReason reason = response.getReason();

    switch (response.getStatus()) {

    case SUCCESS:
    case OK:
        logger.debug("Successfully handled the event message ({}) by '{}'", eventMessage.getIdentifier(),
                eventListener.getName());
        channel.basicAck(deliveryTag, false);
        break;

    case ERROR:
        if (reason.getException().isPresent()) {
            logger.warn("Failed to handle the event message ({}) by '{}' : {}", eventMessage.getIdentifier(),
                    eventListener.getName(), reason.getMessages(), reason.getException().get());
        } else {
            logger.warn("Failed to handle the event message ({}) by '{}' : {}", eventMessage.getIdentifier(),
                    eventListener.getName(), reason.getMessages());
        }
        channel.basicAck(deliveryTag, false);
        break;

    case FAILURE:
        metricRegistry.counter(HANDLE_MESSAGE_ERROR_METRIC).inc();

        final Integer nbAttempt = getIncrementedNbAttempt(message);
        final DateTime time = new DateTime(message.getMessageProperties().getTimestamp());

        LOGGER.debug("Failed to attempt to handle the event message ({}) : {} time(s) by '{}'",
                eventMessage.getIdentifier(), nbAttempt, eventListener.getName());

        if (response.isTemporary()) {
            if (nbAttempt >= maxAttempts) {
                if (DateTime.now().minusHours(requeueThresholdInHours).isBefore(time)) {
                    LOGGER.info("Requeue the event message ({}) in the related queue of '{}'",
                            eventMessage.getIdentifier(), eventListener.getClass().getSimpleName());
                    channel.basicNack(deliveryTag, false, true);
                    return;
                } else {
                    messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(),
                            reason.getException().or(new RuntimeException("Failed to handle event message"))));
                    channel.basicNack(deliveryTag, false, false);
                    return;
                }
            }
        } else if (nbAttempt >= maxAttempts) {
            messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(),
                    reason.getException().or(new RuntimeException("Failed to handle event message"))));
            channel.basicNack(deliveryTag, false, false);
            break;
        }

        throw new MessageHandlerException(eventListener.getClass(),
                reason.getException().or(new KasperEventException(response.getReason().toString())));

    default:
        messageRecoverer.recover(message,
                new MessageHandlerException(eventListener.getClass(), reason.getException().or(
                        new RuntimeException(String.format("Status not managed '%s'", response.getStatus())))));
        channel.basicNack(deliveryTag, false, false);
        break;
    }
}

From source file:cu.uci.uengine.amqp.SubmitsListener.java

@Override
public void onMessage(Message message, Channel channel) throws Exception {

    message.getMessageProperties().setHeader("__TypeId__", "cu.uci.uengine.model.dto.SubmissionDTO");

    try {/* ww  w . ja va 2s  .c  om*/
        SubmissionDTO submissionDTO = (SubmissionDTO) jsonMessageConverter.fromMessage(message);

        Submission submit = new SubmissionDTOToSubmissionAdapter(submissionDTO);

        log.info(String.format("Working on submission: %s", submit.toString()));

        Submission result = engine.call(submit);

        log.info(String.format("Sending sid %s: %s. %s", result.getId(), result.getVerdict(),
                result.getErrorMessage() == null ? "" : result.getErrorMessage()));

        VerdictDTO verdict = new SubmissionToVerdictDTOAdapter(result);

        submitTemplate.convertAndSend(verdict, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setHeader("__TypeId__", "UEngineVerdict");
                return message;
            }
        });

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    } catch (MessageConversionException messageConversionException) {
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        log.error(String.format("Wrong submission format: %s", messageConversionException.getMessage()));
    } catch (Exception ex) {
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        log.error(String.format("Error preocessing message with correlationId: %s",
                message.getMessageProperties().getCorrelationId()));
    }
}

From source file:io.qdb.server.input.RabbitMQInputHandler.java

License:Apache License

@Override
public void start(final Sink sink) throws Exception {
    this.sink = sink;
    final Channel c = ensureChannel();
    c.basicConsume(queue, autoAck, "qdb:" + inputPath, new DefaultConsumer(c) {
        @Override//from  w  ww. ja v  a 2  s. c o m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            boolean ok = false;
            try {
                sink.append(envelope.getRoutingKey(), body);
                if (!autoAck)
                    c.basicAck(envelope.getDeliveryTag(), false);
                ok = true;
            } catch (Exception e) {
                sink.error(e);
            } finally {
                if (!ok) {
                    try {
                        // todo should probably sit on the message for a bit before nacking to prevent storm
                        c.basicNack(envelope.getDeliveryTag(), false, true);
                    } catch (IOException e) {
                        log.debug("Error nacking message: " + e, e);
                    }
                }
            }
        }
    });
}

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);
    }//  w  w  w  . j av  a  2 s. com

    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.ballerinalang.messaging.rabbitmq.nativeimpl.message.BasicNack.java

License:Open Source License

@Override
public void execute(Context context) {
    @SuppressWarnings(RabbitMQConstants.UNCHECKED)
    BMap<String, BValue> messageObject = (BMap<String, BValue>) context.getRefArgument(0);
    Channel channel = RabbitMQUtils.getNativeObject(messageObject, RabbitMQConstants.CHANNEL_NATIVE_OBJECT,
            Channel.class, context);
    long deliveryTag = (long) messageObject.getNativeData(RabbitMQConstants.DELIVERY_TAG);
    boolean multiple = context.getBooleanArgument(0);
    boolean requeue = context.getBooleanArgument(1);
    boolean multipleAck = ChannelUtils.validateMultipleAcknowledgements(messageObject);
    boolean ackMode = ChannelUtils.validateAckMode(messageObject);
    if (!multipleAck && ackMode) {
        try {/*  w ww .jav  a 2  s  .  c o m*/
            channel.basicNack(deliveryTag, multiple, requeue);
        } catch (IOException exception) {
            LOGGER.error("I/O Error occurred while negatively acknowledging the message");
            RabbitMQUtils.returnError("Error occurred while negatively acknowledging the message", context,
                    exception);
        } catch (AlreadyClosedException exception) {
            LOGGER.error(RabbitMQConstants.CHANNEL_CLOSED_ERROR);
            RabbitMQUtils.returnError(RabbitMQConstants.CHANNEL_CLOSED_ERROR, context, exception);
        }
    } else if (multipleAck && ackMode) {
        RabbitMQUtils.returnError(RabbitMQConstants.MULTIPLE_ACK_ERROR, context,
                new RabbitMQConnectorException(RabbitMQConstants.MULTIPLE_ACK_ERROR));
    } else {
        RabbitMQUtils.returnError(RabbitMQConstants.ACK_MODE_ERROR, context,
                new RabbitMQConnectorException(RabbitMQConstants.ACK_MODE_ERROR));
    }
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public void cleanQueue(String queue, String match) throws IOException, InterruptedException {
    logger.trace(queue.concat(": ").concat(match));
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
    Set seen = new HashSet();
    while (delivery != null) {
        String body = new String(delivery.getBody());
        if (seen.contains(body)) {
            break;
        }/*from  ww  w.  jav a2  s  . co  m*/
        if (body.contains(match)) {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
            seen.add(body);
        }
        delivery = consumer.nextDelivery(1000);
    }
    channel.close();
    closeRmqConn(connectionRcv);
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public List<File> getFiles(String queue, Path outFolder, boolean ack) throws IOException, InterruptedException {
    List files = new ArrayList();
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);

    Set seen = new HashSet();

    while (delivery != null) {
        String host = delivery.getProperties().getHeaders().get("host").toString();
        File outTo = Paths.get(outFolder.toString(), host + ".tar.gz").toFile();
        FileUtils.writeByteArrayToFile(outTo, delivery.getBody());
        if (ack) {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {/*from   ww w.j  a va2 s .c  om*/
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
        }
        if (seen.contains(delivery.getProperties().getHeaders().get("host"))) {
            break;
        }
        seen.add(delivery.getProperties().getHeaders().get("host"));
        files.add(outTo);
        logger.info(queue + " retrieved: " + outTo.getAbsolutePath());
        delivery = consumer.nextDelivery(1000);
    }
    logger.warn("getFiles done");
    channel.close();
    closeRmqConn(connectionRcv);
    return files;
}