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:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQConsumerActor.java

License:Open Source License

private void handleDelivery(final Delivery delivery) {
    final BasicProperties properties = delivery.getProperties();
    final Envelope envelope = delivery.getEnvelope();
    final byte[] body = delivery.getBody();
    final String hashKey = envelope.getExchange() + ":" + envelope.getRoutingKey();

    Map<String, String> headers = null;
    try {// w w  w.  j a  v  a  2 s . c o  m
        final String correlationId = properties.getCorrelationId();
        LogUtil.enhanceLogWithCorrelationId(log, correlationId);
        if (log.isDebugEnabled()) {
            log.debug("Received message from RabbitMQ ({}//{}): {}", envelope, properties,
                    new String(body, StandardCharsets.UTF_8));
        }
        headers = extractHeadersFromMessage(properties, envelope);
        final ExternalMessageBuilder externalMessageBuilder = ExternalMessageFactory
                .newExternalMessageBuilder(headers);
        final String contentType = properties.getContentType();
        final String text = new String(body, CharsetDeterminer.getInstance().apply(contentType));
        if (shouldBeInterpretedAsBytes(contentType)) {
            externalMessageBuilder.withBytes(body);
        } else {
            externalMessageBuilder.withTextAndBytes(text, body);
        }
        externalMessageBuilder.withAuthorizationContext(authorizationContext);
        externalMessageBuilder.withEnforcement(headerEnforcementFilterFactory.getFilter(headers));
        externalMessageBuilder.withHeaderMapping(headerMapping);
        externalMessageBuilder.withSourceAddress(sourceAddress);
        final ExternalMessage externalMessage = externalMessageBuilder.build();
        inboundMonitor.success(externalMessage);
        forwardToMappingActor(externalMessage, hashKey);
    } catch (final DittoRuntimeException e) {
        log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage());
        if (headers != null) {
            // send response if headers were extracted successfully
            forwardToMappingActor(e.setDittoHeaders(DittoHeaders.of(headers)), hashKey);
            inboundMonitor.failure(headers, e);
        } else {
            inboundMonitor.failure(e);
        }
    } catch (final Exception e) {
        log.warning("Processing delivery {} failed: {}", envelope.getDeliveryTag(), e.getMessage());
        if (headers != null) {
            inboundMonitor.exception(headers, e);
        } else {
            inboundMonitor.exception(e);
        }
    }
}

From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQConsumerActor.java

License:Open Source License

private static Map<String, String> extractHeadersFromMessage(final BasicProperties properties,
        final Envelope envelope) {

    final Map<String, String> headersFromProperties = getHeadersFromProperties(properties.getHeaders());

    // set headers specific to rmq messages
    if (properties.getReplyTo() != null) {
        headersFromProperties.put(ExternalMessage.REPLY_TO_HEADER, properties.getReplyTo());
    }/*ww  w. j  a  v a2s . c o m*/
    if (properties.getCorrelationId() != null) {
        headersFromProperties.put(DittoHeaderDefinition.CORRELATION_ID.getKey(), properties.getCorrelationId());
    }
    if (properties.getContentType() != null) {
        headersFromProperties.put(ExternalMessage.CONTENT_TYPE_HEADER, properties.getContentType());
    }
    headersFromProperties.put(MESSAGE_ID_HEADER, Long.toString(envelope.getDeliveryTag()));

    return headersFromProperties;
}

From source file:org.eclipse.hono.client.AmqpConnectorClient.java

License:Open Source License

private void declareBindQueue() throws IOException {
    channel = connectionManager.getChannel();
    channel.queueDeclare(clientId, true, false, false, emptyMap());
    LOGGER.info("declared a queue with subject " + clientId);
    channel.queueBind(clientId, OUT, clientId);
    LOGGER.info("bind queue to routingkey " + clientId);
    consumerTag = channel.basicConsume(clientId, new DefaultConsumer(channel) {
        @Override//from  www .j av a 2 s  .  c o m
        public void handleDelivery(final String consumerTag, final Envelope envelope,
                final AMQP.BasicProperties properties, final byte[] body) throws IOException {
            final String routingKey = envelope.getRoutingKey();
            getChannel().basicAck(envelope.getDeliveryTag(), false);
            final String topic = properties.getHeaders().get(TOPIC_HEADER).toString();
            LOGGER.debug("{} received message for topic '{}'", routingKey, topic);
            delegateToTopicConsumer(properties, body, topic);
        }
    });
}

From source file:org.elasticsoftware.elasticactors.rabbitmq.cpt.LocalMessageQueue.java

License:Apache License

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
        throws IOException {
    try {/* w ww. j  a  v  a  2  s. co m*/
        messageAcker.deliver(envelope.getDeliveryTag());
        // execute on seperate (thread bound) executor
        queueExecutor.execute(new RabbitMQMessageHandler(queueName, body, internalMessageDeserializer,
                messageHandler, new RabbitMQAck(envelope), logger));
    } catch (Exception e) {
        logger.error(
                "Unexpected Exception on handleDelivery.. Acking the message so it will not clog up the system",
                e);
        messageAcker.ack(envelope.getDeliveryTag());
    }
}

From source file:org.graylog2.inputs.amqp.AMQPConsumer.java

License:Open Source License

public Consumer createConsumer(final Channel channel) {
    return new DefaultConsumer(channel) {
        @Override// w w  w  . ja va 2  s  . co m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            try {
                // The duplication here is a bit unfortunate. Improve by having a Processor Interface.
                switch (queueConfig.getInputType()) {
                case GELF:
                    GELFMessage gelf = new GELFMessage(body);
                    try {
                        gelfProcessor.messageReceived(gelf);
                    } catch (BufferOutOfCapacityException e) {
                        LOG.warn("ProcessBufferProcessor is out of capacity. Requeuing message!");
                        channel.basicReject(envelope.getDeliveryTag(), true);
                        reQueuedMessages.mark();
                        return;
                    }

                    handledGELFMessages.mark();
                    break;
                case SYSLOG:
                    try {
                        syslogProcessor.messageReceived(new String(body), connection.getAddress());
                    } catch (BufferOutOfCapacityException e) {
                        LOG.warn("ProcessBufferProcessor is out of capacity. Requeuing message!");
                        channel.basicReject(envelope.getDeliveryTag(), true);
                        reQueuedMessages.mark();
                        return;
                    }

                    handledSyslogMessages.mark();
                    break;
                }

                channel.basicAck(envelope.getDeliveryTag(), false);
                handledMessages.mark();
            } catch (Exception e) {
                LOG.error("Could not handle message from AMQP.", e);
            }
        }
    };
}

From source file:org.graylog2.inputs.amqp.Consumer.java

License:Open Source License

public void run() throws IOException {
    if (!isConnected()) {
        connect();/* www .  j a  v  a  2s  . c o  m*/
    }

    final MessagePack msgpack = new MessagePack();

    channel.basicConsume(queue, false, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            long deliveryTag = envelope.getDeliveryTag();

            try {
                totalBytesRead.addAndGet(body.length);
                lastSecBytesReadTmp.addAndGet(body.length);

                RadioMessage msg = msgpack.read(body, RadioMessage.class);

                if (!msg.strings.containsKey("message") || !msg.strings.containsKey("source")
                        || msg.timestamp <= 0) {
                    LOG.error("Incomplete AMQP message. Skipping.");
                    channel.basicAck(deliveryTag, false);
                }

                Message event = new Message(msg.strings.get("message"), msg.strings.get("source"),
                        new DateTime(msg.timestamp));

                event.addStringFields(msg.strings);
                event.addLongFields(msg.longs);
                event.addDoubleFields(msg.doubles);

                processBuffer.insertCached(event, sourceInput);

            } catch (Exception e) {
                LOG.error("Error while trying to process AMQP message.", e);
            }

            channel.basicAck(deliveryTag, false);
        }
    });
}

From source file:org.graylog2.inputs.transports.AmqpConsumer.java

License:Open Source License

public void run() throws IOException {
    if (!isConnected()) {
        connect();//  w ww  .  ja  va2 s  .  c om
    }

    for (int i = 0; i < parallelQueues; i++) {
        final String queueName = String.format(queue, i);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.basicConsume(queueName, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                long deliveryTag = envelope.getDeliveryTag();
                try {
                    totalBytesRead.addAndGet(body.length);
                    lastSecBytesReadTmp.addAndGet(body.length);

                    final RawMessage rawMessage = new RawMessage(body);

                    // TODO figure out if we want to unsubscribe after a certain time, or if simply blocking is enough here
                    if (amqpTransport.isThrottled()) {
                        amqpTransport.blockUntilUnthrottled();
                    }

                    sourceInput.processRawMessage(rawMessage);
                    channel.basicAck(deliveryTag, false);
                } catch (Exception e) {
                    LOG.error("Error while trying to process AMQP message, requeuing message", e);
                    if (channel.isOpen()) {
                        channel.basicNack(deliveryTag, false, true);
                    }
                }
            }
        });
    }
}

From source file:org.iplantcollaborative.ClientRegistrar.java

License:Apache License

public void connect() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.serverConf.getHostname());
    factory.setPort(this.serverConf.getPort());
    factory.setUsername(this.serverConf.getUserId());
    factory.setPassword(this.serverConf.getUserPwd());
    factory.setVirtualHost(this.serverConf.getVhostPublish());

    factory.setAutomaticRecoveryEnabled(true);

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

    LOG.info("client registrar connected - " + this.serverConf.getHostname() + ":" + this.serverConf.getPort());

    this.channel.basicQos(1);
    this.channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "#");

    this.consumer = new DefaultConsumer(this.channel) {
        @Override/*from w w w  . j  ava2  s .com*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");

            LOG.info("registration - " + message);

            BasicProperties replyProps = new BasicProperties.Builder()
                    .correlationId(properties.getCorrelationId()).build();

            ARequest request = RequestFactory.getRequestInstance(message);

            // handle lease request
            if (request instanceof RequestLease) {
                ResponseLease res = lease((RequestLease) request);
                String response_json = serializer.toJson(res);

                if (properties.getReplyTo() != null) {
                    channel.basicPublish("", properties.getReplyTo(), replyProps, response_json.getBytes());
                } else {
                    LOG.error("unable to return response. reply_to field is null");
                }
            } else {
                LOG.error("Unknown request : " + message);
            }

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

    this.workerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                channel.basicConsume(QUEUE_NAME, false, consumer);
                LOG.info("Waiting for registrations");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming message", ex);
            }
        }
    });
    this.workerThread.start();
}

From source file:org.iplantcollaborative.DataStoreMessageReceiver.java

License:Apache License

public void connect() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.serverConf.getHostname());
    factory.setPort(this.serverConf.getPort());
    factory.setUsername(this.serverConf.getUserId());
    factory.setPassword(this.serverConf.getUserPwd());
    factory.setVirtualHost(this.serverConf.getVhostSubscribe());

    factory.setAutomaticRecoveryEnabled(true);

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

    LOG.info("subscriber connected - " + this.serverConf.getHostname() + ":" + this.serverConf.getPort());

    this.channel.basicQos(1);
    this.queueName = this.channel.queueDeclare().getQueue();
    this.channel.queueBind(this.queueName, EXCHANGE_NAME, "#");

    this.consumer = new DefaultConsumer(this.channel) {
        @Override/*from   w w  w  .  j av a2 s  .  c  om*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");

            LOG.debug("subscribe - " + envelope.getRoutingKey() + ":" + message);

            DataStoreMessageProcessor processor = binder.getProcessor();
            if (processor != null) {
                processor.process(envelope.getRoutingKey(), message);
            } else {
                LOG.error("processor not registered");
            }

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

    this.workerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                channel.basicConsume(queueName, consumer);
                LOG.info("Waiting for messages");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming a message", ex);
            }
        }
    });
    this.workerThread.start();
}

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

License:Open Source License

private void addEnvelopeProperties(final Map<String, Object> messageProperties, final Envelope envelope) {
    if (envelope == null)
        return;//ww  w . ja  v  a  2s . co  m

    putIfNonNull(messageProperties, AmqpConstants.DELIVERY_TAG, envelope.getDeliveryTag());
    putIfNonNull(messageProperties, AmqpConstants.REDELIVER, envelope.isRedeliver());
    putIfNonNull(messageProperties, AmqpConstants.EXCHANGE, envelope.getExchange());
    putIfNonNull(messageProperties, AmqpConstants.ROUTING_KEY, envelope.getRoutingKey());
}