Example usage for com.rabbitmq.client Channel basicAck

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

Introduction

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

Prototype

void basicAck(long deliveryTag, boolean multiple) throws IOException;

Source Link

Document

Acknowledge one or several received messages.

Usage

From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java

License:Apache License

@Override
public void run() {

    Connection connection = null;
    Channel channel = null;
    try {/*from w w w .ja  v  a  2 s . c o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname);
        factory.setHost(hostname);

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

        channel.queueDeclare(rpcQueueName, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rpcQueueName, false, consumer);

        while (true) {
            String response = null;

            // Block and fetch next msg from queue
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                logger.trace("Received msg: " + message);

                // Convert the message to a JSON request object
                JSONObject request = (JSONObject) JSONValue.parse(message);

                // Delegate to the server request handler for handling the
                // request and computing an answer
                JSONObject reply = serverRequestHandler.handleRequest(request);

                // Convert the answer back into a string for replying to
                // client
                response = reply.toJSONString();
            } catch (Exception e) {
                logger.error(" Exception in MQDAemon run()/while true] " + e.toString());
                response = "wrong";
            } finally {
                logger.trace("Returning answer: " + response);
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                logger.trace("Answer acknowledged.");
            }
        }
    } catch (Exception e) {
        logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

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 {/*from  www.ja  v  a2 s .c o  m*/
        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:dfki.sb.rabbitmqjava.RabbitMQObjectStreamServer.java

License:Open Source License

private static void processSendAndRecivePackets(QueueingConsumer consumer, Channel channel)
        throws InterruptedException, IOException {
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();
        BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                .build();/*from w w  w  .jav a 2  s  .  com*/
        try {
            byte[] body = delivery.getBody();
            if (body.length == 0) {
                break;
            } else {
                Object obj = SerializationUtils.deserialize(body);
                if (obj instanceof MarketData) {
                    MarketData response = sendMarketData((MarketData) obj);
                    channel.basicPublish("", props.getReplyTo(), replyProps,
                            SerializationUtils.serialize(response));
                } else {
                    QuoteRequest response = sendQuoteRequest((QuoteRequest) obj);
                    channel.basicPublish("", props.getReplyTo(), replyProps,
                            SerializationUtils.serialize(response));
                }
            }
        } catch (IOException e) {
            System.out.println(" [.] " + e.toString());
        } finally {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    }
}

From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java

License:Open Source License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {/* w  w w.  ja  va  2 s . co  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println("Starting server waiting for client requests:");
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();
            DataInputStream dis = new DataInputStream(
                    new BufferedInputStream(new ByteArrayInputStream(delivery.getBody())));
            try {
                int type = dis.readInt();
                byte[] response;
                if (type == 2) {
                    response = handleMarketRequest(dis);
                } else {
                    response = handleQuoteRequest(dis);
                }
                channel.basicPublish("", props.getReplyTo(), replyProps, response);
                dis.close();
            } catch (IOException | ClassNotFoundException e) {
                System.out.println(" [.] " + e.toString());
            } finally {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:dk.bankjsonrabbit.controller.CalculateQuote.java

public static void receiveMessages() throws IOException, InterruptedException, TimeoutException {
    gson = new Gson();

    HashMap<String, Object> objects = Receive.setUpReceiver();

    QueueingConsumer consumer = (QueueingConsumer) objects.get("consumer");
    Channel channel = (Channel) objects.get("channel");

    LoanRequestDTO loanRequestDTO;//from www  .  ja  v  a  2  s  .  c  o  m
    LoanResponseDTO loanResponseDTO;

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

        AMQP.BasicProperties props = delivery.getProperties();
        AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                .correlationId(props.getCorrelationId()).replyTo(props.getReplyTo()).headers(props.getHeaders())
                .build();

        loanRequestDTO = gson.fromJson(message, LoanRequestDTO.class);

        double interestRate = new Random().nextDouble() * 20;

        loanResponseDTO = new LoanResponseDTO(interestRate, loanRequestDTO.getSsn());

        System.out.println(loanResponseDTO.toString());

        sendMessage(loanResponseDTO, replyProps);
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

}

From source file:dk.getcreditscore.controller.CalculateCreditScore.java

public static void receiveMessages() throws IOException, InterruptedException {
    gson = new Gson();

    HashMap<String, Object> objects = Receive.setUpReceiver();

    QueueingConsumer consumer = (QueueingConsumer) objects.get("consumer");
    Channel channel = (Channel) objects.get("channel");

    LoanRequestDTO loanRequestDTO;/*from   w  ww.  ja v  a2s.  c  o  m*/

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

        loanRequestDTO = gson.fromJson(message, LoanRequestDTO.class);

        CreditScoreService_Service service = new CreditScoreService_Service();
        int creditScore = service.getCreditScoreServicePort().creditScore(loanRequestDTO.getSsn());

        loanRequestDTO.setCreditScore(creditScore);

        System.out.println(loanRequestDTO.toString());

        sendMessage(loanRequestDTO);

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

}

From source file:dk.normalizer.controller.NormalizeFromBankJSON.java

public static void receiveMessages() throws IOException, InterruptedException {
    gson = new Gson();

    HashMap<String, Object> objects = Receive.setUpReceiver();

    QueueingConsumer consumer = (QueueingConsumer) objects.get("consumer");
    Channel channel = (Channel) objects.get("channel");

    LoanResponseDTO loanResponseDTO;//from w ww .  j a v  a2s  .c o  m

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        AMQP.BasicProperties props = delivery.getProperties();
        AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                .correlationId(props.getCorrelationId()).build();
        System.out.println(props.getCorrelationId());
        System.out.println(props.getReplyTo());

        System.out.println(message);

        loanResponseDTO = gson.fromJson(message, LoanResponseDTO.class);

        System.out.println(loanResponseDTO.toString());

        //          sendMessage();

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

}

From source file:dk.normalizer.controller.NormalizeFromBankRabbit.java

public static void receiveMessages() throws IOException, InterruptedException {
    gson = new Gson();

    HashMap<String, Object> objects = Receive.setUpReceiver();

    QueueingConsumer consumer = (QueueingConsumer) objects.get("consumer");
    Channel channel = (Channel) objects.get("channel");

    LoanResponseDTO loanResponseDTO;/*from w  w  w  .  j  a  va  2 s. c o  m*/

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        //          AMQP.BasicProperties props = delivery.getProperties();
        //          AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(props.getCorrelationId()).build();
        //          System.out.println(props.getCorrelationId());
        //          System.out.println(props.getReplyTo());

        //          loanResponseDTO = gson.fromJson(message, LoanResponseDTO.class);

        //          System.out.println(loanResponseDTO.toString());

        //          sendMessage();

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

}

From source file:dk.normalizer.controller.NormalizeFromBankService.java

public static void receiveMessages() throws IOException, InterruptedException {
    gson = new Gson();

    HashMap<String, Object> objects = Receive.setUpReceiver();

    QueueingConsumer consumer = (QueueingConsumer) objects.get("consumer");
    Channel channel = (Channel) objects.get("channel");

    LoanResponseDTO loanResponseDTO;//from   w ww  .  j av a 2  s. c  o m

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

        //          AMQP.BasicProperties props = delivery.getProperties();
        //          AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(props.getCorrelationId()).build();
        //          System.out.println(props.getCorrelationId());
        //          System.out.println(props.getReplyTo());

        System.out.println("Message: " + message);

        loanResponseDTO = gson.fromJson(message, LoanResponseDTO.class);

        System.out.println(loanResponseDTO.toString());

        //          sendMessage();

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

}

From source file:dk.normalizer.controller.NormalizeFromBankXML.java

public static void receiveMessages() throws IOException, InterruptedException {
    gson = new Gson();

    HashMap<String, Object> objects = Receive.setUpReceiver();

    QueueingConsumer consumer = (QueueingConsumer) objects.get("consumer");
    Channel channel = (Channel) objects.get("channel");

    LoanResponseDTO loanResponseDTO;/*  w  ww . j av  a  2s  .c o  m*/
    XStream xStream = new XStream();

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

        AMQP.BasicProperties props = delivery.getProperties();
        AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                .correlationId(props.getCorrelationId()).build();
        System.out.println("CorrelationID = " + props.getCorrelationId());
        //          System.out.println(props.getReplyTo());
        System.out.println(message);

        loanResponseDTO = (LoanResponseDTO) xStream.fromXML(message);

        System.out.println("Converted from XML: " + loanResponseDTO.toString());

        //          sendMessage();

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

}