Example usage for com.rabbitmq.client Envelope getDeliveryTag

List of usage examples for com.rabbitmq.client Envelope getDeliveryTag

Introduction

In this page you can find the example usage for com.rabbitmq.client Envelope getDeliveryTag.

Prototype

public long getDeliveryTag() 

Source Link

Document

Get the delivery tag included in this parameter envelope

Usage

From source file:com.caucho.v5.pipe.rabbit.RabbitPipeImpl.java

License:Open Source License

@Override
protected void onInitReceive() {
    if (_consumerTag != null) {
        return;//ww w  . j  a v a  2 s. c  o  m
    }

    try {
        boolean isAutoAck = false;

        _consumerTag = _channel.basicConsume(_config.routingKey(), isAutoAck, new DefaultConsumer(_channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                RabbitMessage msg = RabbitMessage.newMessage().body(body).properties(properties)
                        .redeliver(envelope.isRedeliver());

                long deliveryTag = envelope.getDeliveryTag();

                _self.onRabbitReceive(msg, (Void, e) -> {
                    if (e != null) {
                        _channel.basicReject(deliveryTag, false);
                    } else {
                        _channel.basicAck(deliveryTag, false);
                    }
                });
            }
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.digispherecorp.enterprise.rabbitmq.ra.work.PublishSubcribeRabbitMQWork.java

@Override
public void run() {
    try {//from  ww w  . j  av  a2s.c  o  m
        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO,
                "Work Schedule Polling started @ ".concat(uuid));

        if (ipsm == null) {
            try {
                Class<?> className = Class
                        .forName(((RabbitMQActivationSpec) activationSpec).getDestinationType());
                ipsm = (IPublishSubscribeMessage) className.getConstructor().newInstance();
            } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                    | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                Logger.getLogger(BootStrapRabbitMQWork.class.getName()).log(Level.SEVERE,
                        ex.getLocalizedMessage(), ex);
            }
        }
        final Channel channel;
        RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance();
        if (instance.getConnectionRequestInfo(activationSpec) == null) {
            instance.setConnectionRequestInfo(activationSpec,
                    new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(),
                            ((RabbitMQActivationSpec) activationSpec).getPassword(),
                            ((RabbitMQActivationSpec) activationSpec).getHost(),
                            ((RabbitMQActivationSpec) activationSpec).getPort(),
                            ((RabbitMQActivationSpec) activationSpec).getVirtualHost()));
        }
        try {
            connection = instance.getConnection();
            channel = connection.createChannel();

            channel.exchangeDeclare(((RabbitMQActivationSpec) activationSpec).getExchangeName(),
                    ipsm.getSubscribeType(), isExchangeDurabe(ipsm));

            final Consumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleConsumeOk(String consumerTag) {
                    super.handleConsumeOk(consumerTag);
                }

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    if (!envelope.isRedeliver()) {
                        try {
                            RabbitMQMessage mQMessage = new RabbitMQMessage();
                            mQMessage.getMessages().add(body);
                            try {
                                receiveMessages(mQMessage);
                            } catch (ResourceException ex) {
                                Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE,
                                        ex.getLocalizedMessage(), ex);
                            }
                        } finally {
                            channel.basicAck(envelope.getDeliveryTag(), true);
                        }
                    }
                }
            };
            channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer);
        } catch (IOException ex) {
            Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE,
                    ex.getLocalizedMessage(), ex);
        }
    } catch (Exception ex) {
        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    }
}

From source file:com.digispherecorp.enterprise.rabbitmq.ra.work.QueueRabbitMQWork.java

@Override
public void run() {
    try {//from  w  ww.ja v  a  2 s .  c om

        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO,
                "Work Schedule Polling started @ ".concat(uuid));

        final Channel channel;
        RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance();
        if (instance.getConnectionRequestInfo(activationSpec) == null) {
            instance.setConnectionRequestInfo(activationSpec,
                    new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(),
                            ((RabbitMQActivationSpec) activationSpec).getPassword(),
                            ((RabbitMQActivationSpec) activationSpec).getHost(),
                            ((RabbitMQActivationSpec) activationSpec).getPort(),
                            ((RabbitMQActivationSpec) activationSpec).getVirtualHost()));
        }
        try {
            connection = instance.getConnection();
            channel = connection.createChannel();
            channel.queueDeclarePassive(((RabbitMQActivationSpec) activationSpec).getQueueName());
            channel.basicQos(0);

            final Consumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleConsumeOk(String consumerTag) {
                    super.handleConsumeOk(consumerTag);
                }

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    if (!envelope.isRedeliver()) {
                        try {
                            RabbitMQMessage mQMessage = new RabbitMQMessage();
                            mQMessage.getMessages().add(body);
                            try {
                                receiveMessages(mQMessage);
                            } catch (ResourceException ex) {
                                Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE,
                                        ex.getLocalizedMessage(), ex);
                            }
                        } finally {
                            channel.basicAck(envelope.getDeliveryTag(), true);
                        }
                    }
                }
            };
            channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer);
        } catch (IOException ex) {
            Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE,
                    ex.getLocalizedMessage(), ex);
        }
    } catch (Exception ex) {
        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    }
}

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

License:Apache License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
        throws IOException {
    ProtocolResponse protocolResponse = null;
    ProtocolRequest<T> request = null;
    try {//from  w w  w.  j  av a2s .  c o  m
        request = mapper.readValue(body, new TypeReference<ProtocolRequest<T>>() {
        });
        T response = request.getCallable().call();
        protocolResponse = new ProtocolResponse<T>(response);
    } catch (Exception e) {
        logger.error("Error: " + e);
        protocolResponse = new ProtocolResponse(BifrostException.ErrorCode.APPLICATION_ERROR,
                "Application level error: " + e.getMessage());
    }
    try {
        if (null != request && request.isResponseReturned()) {
            AMQP.BasicProperties replyProperties = new AMQP.BasicProperties.Builder()
                    .correlationId(properties.getCorrelationId()).build();
            if (null != properties.getReplyTo()) {
                getChannel().basicPublish("", properties.getReplyTo(), replyProperties,
                        mapper.writeValueAsBytes(protocolResponse));
            }
        }
        getChannel().basicAck(envelope.getDeliveryTag(), false);

    } catch (Exception e) {
        logger.error("Error occurred returning: ", e);
    }

}

From source file:com.hpe.caf.util.rabbitmq.DefaultRabbitConsumerTest.java

License:Apache License

@Test
public void testProcessDelivery() throws InterruptedException, IOException {
    BlockingQueue<Event<QueueConsumer>> events = new LinkedBlockingQueue<>();
    CountDownLatch latch = new CountDownLatch(1);
    TestQueueConsumerImpl impl = new TestQueueConsumerImpl(latch);
    DefaultRabbitConsumer con = new DefaultRabbitConsumer(events, impl);
    new Thread(con).start();
    long tag = 100L;
    byte[] body = "data".getBytes(StandardCharsets.UTF_8);
    Envelope env = Mockito.mock(Envelope.class);
    Mockito.when(env.getDeliveryTag()).thenReturn(tag);
    events.offer(new ConsumerDeliverEvent(new Delivery(env, body)));
    Assert.assertTrue(latch.await(DefaultRabbitConsumer.POLL_PERIOD, TimeUnit.MILLISECONDS));
    Assert.assertArrayEquals(body, impl.getLastDelivery().getMessageData());
}

From source file:com.mycompany.javateste.queues.worktasks.Worker.java

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

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);/*from   w w w. ja  va 2s. c om*/

    final 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 '" + message + "'");
            try {
                doWork(message);
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        }
    };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
}

From source file:com.mycompany.mavenproject1.RMQConsumer.java

License:Open Source License

/**
 * Returns and acknowledges the message at the top of a given queue
 *
 * @return//  w  w w.ja v  a2s.c o  m
 */
@SuppressWarnings("override")
public String ackMessage(String queue) {

    //make sure message var is empty
    message = "";

    createChannel(queue);
    try {
        channel.basicQos(1);
    } catch (IOException ex) {
        Logger.getLogger(RMQConsumer.class.getName()).log(Level.SEVERE, null, ex);
    }

    final Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            {
                message = new String(body, "UTF-8");

                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        }
    };

    try {
        channel.basicConsume(queue, false, consumer);
    } catch (IOException ex) {
        Logger.getLogger(RMQConsumer.class.getName()).log(Level.SEVERE, null, ex);
    }
    while (message.equals("")) {

    }
    destroyChannel();
    return message;
}

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

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//from   ww w .  j  a  v  a2 s  . c  o m
 */
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//from   ww w . j av a  2 s .  com
 */
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.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java

License:Apache License

public Exchange createRabbitExchange(Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
    Exchange exchange = new DefaultExchange(getVramelContext(), getExchangePattern(getExchangeType()));

    Message message = new DefaultMessage();
    exchange.setIn(message);//w w  w .  j  a  va 2 s.  c  o m

    message.setHeader(RabbitMQConstants.ROUTING_KEY, envelope.getRoutingKey());
    message.setHeader(RabbitMQConstants.EXCHANGE_NAME, envelope.getExchange());
    message.setHeader(RabbitMQConstants.DELIVERY_TAG, envelope.getDeliveryTag());

    Map<String, Object> headers = properties.getHeaders();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            // Convert LongStrings to String.
            if (entry.getValue() instanceof LongString) {
                message.setHeader(entry.getKey(), entry.getValue().toString());
            } else if (entry.getKey().equals(RabbitMQConstants.VRAMEL_SERIALIZABLE_HEADERS)) {
                SerializableHeaderContainer serializedHeaders = new SerializableHeaderContainer(
                        (byte[]) entry.getValue());
                serializedHeaders.deserializeInto(message);
            } else {
                message.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    message.setBody(body);

    return exchange;
}