Example usage for com.rabbitmq.client Delivery getBody

List of usage examples for com.rabbitmq.client Delivery getBody

Introduction

In this page you can find the example usage for com.rabbitmq.client Delivery getBody.

Prototype

public byte[] getBody() 

Source Link

Document

Retrieve the message body.

Usage

From source file:it.polimi.hegira.queue.TestQueue.java

License:Apache License

/**
 * Test method for {@link it.polimi.hegira.queue.Queue#publish(java.lang.String, byte[])}.
 * @throws QueueException //w w w .ja v a 2 s. c  om
 */
public void testPublish() {
    String logs = Thread.currentThread().getContextClassLoader().getResource(Constants.LOGS_PATH).getFile();
    PropertyConfigurator.configure(logs);

    String RK = "toApiServer", MSG = "test message";
    try {
        Queue queue = new Queue();
        queue.publish(RK, MSG.getBytes());
        QueueingConsumer consumer = queue.getConsumer();

        Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        String routingKey = delivery.getEnvelope().getRoutingKey();
        assertEquals(message, MSG);
        assertEquals(routingKey, RK);

    } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException e) {
        e.printStackTrace();
        fail("Error retrieving the message from the queue");
    } catch (QueueException e) {
        e.printStackTrace();
        fail("Queue error");
    }
}

From source file:joram.amqp.PersistenceSimpleTest.java

License:Open Source License

public void recover2() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    channel.txSelect();/*ww w  .ja  v a 2s .  c  o  m*/
    for (int i = 0; i < 5; i++) {
        channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                "this is a test message !!!".getBytes());
    }
    channel.txCommit();

    killAgentServer((short) 0);

    startAgentServer((short) 0);
    Thread.sleep(500);

    connection = cnxFactory.newConnection();
    channel = connection.createChannel();
    declareOk = channel.queueDeclarePassive("testqueue");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(declareOk.getQueue(), true, consumer);

    for (int i = 0; i < 5; i++) {
        Delivery msg = consumer.nextDelivery(1000);
        assertNotNull(msg);
        assertEquals("this is a test message !!!", new String(msg.getBody()));
    }

    Delivery msg = consumer.nextDelivery(1000);
    assertNull(msg);

    channel.queueDelete(declareOk.getQueue());

}

From source file:normalizerbankfour.NormalizerBankFour.java

/**
 * @param args the command line arguments
 *//*from   w w w  .jav a2s .co m*/
public static void main(String[] args) {
    ConnectionCreator creator = ConnectionCreator.getInstance();
    try {
        channelIn = creator.createChannel();
        channelIn.queueDeclare(IN_QUEUE, false, false, false, null);
        channelOut = creator.createChannel();
        channelOut.queueDeclare(OUT_QUEUE, false, false, false, null);
        consumer = new QueueingConsumer(channelIn);
        channelIn.basicConsume(IN_QUEUE, consumer);

    } catch (IOException ex) {
        Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex);
    }

    while (true) {
        try {
            System.out.println("Normalizer for BankFour is running");
            Delivery delivery = consumer.nextDelivery();
            channelIn.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            System.out.println("Got message: " + new String(delivery.getBody()));
            String message = normalizeMessage(new String(delivery.getBody()));
            BasicProperties probs = new BasicProperties().builder()
                    .correlationId(delivery.getProperties().getCorrelationId()).build();
            channelOut.basicPublish("", OUT_QUEUE, probs, message.getBytes());
        } catch (InterruptedException ex) {
            Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ShutdownSignalException ex) {
            Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ConsumerCancelledException ex) {
            Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NormalizerBankFour.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:normalizerbankthree.NormalizerBankThree.java

/**
 * @param args the command line arguments
 *///from  www  .j a v a2  s . co  m
public static void main(String[] args) {
    ConnectionCreator creator = ConnectionCreator.getInstance();
    try {
        channelIn = creator.createChannel();
        channelIn.queueDeclare(IN_QUEUE, false, false, false, null);
        channelOut = creator.createChannel();
        channelOut.queueDeclare(OUT_QUEUE, false, false, false, null);
        consumer = new QueueingConsumer(channelIn);
        channelIn.basicConsume(IN_QUEUE, true, consumer);

    } catch (IOException ex) {
        Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("Normalizer for Bankthree is running");
    while (true) {
        try {
            Delivery delivery = consumer.nextDelivery();
            System.out.println("Got message: " + new String(delivery.getBody()));
            String message = normalizeMessage(new String(delivery.getBody()));
            BasicProperties probs = new BasicProperties().builder()
                    .correlationId(delivery.getProperties().getCorrelationId()).build();
            channelOut.basicPublish("", OUT_QUEUE, probs, message.getBytes());
            System.out.println("reply: " + message);
        } catch (InterruptedException ex) {
            Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ShutdownSignalException ex) {
            Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ConsumerCancelledException ex) {
            Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NormalizerBankThree.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.apache.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(final InputRowParser<ByteBuffer> firehoseParser, File temporaryDirectory)
        throws IOException {
    ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory);
    Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries())
            .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds()))
            .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds())));

    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = Connections.create(lyraOptions, lyraConfig);

    connection.addShutdownListener(new ShutdownListener() {
        @Override/* w  w w.  j a  va2 s . c om*/
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest row as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private InputRow nextRow;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        private Iterator<InputRow> nextIterator = Collections.emptyIterator();

        @Override
        public boolean hasMore() {
            nextRow = null;
            try {
                if (nextIterator.hasNext()) {
                    nextRow = nextIterator.next();
                    return true;
                }
                // Wait for the next delivery. This will block until something is available.
                final Delivery delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    nextIterator = firehoseParser.parseBatch(ByteBuffer.wrap(delivery.getBody())).iterator();
                    if (nextIterator.hasNext()) {
                        nextRow = nextIterator.next();
                        // If delivery is non-null, we report that there is something more to process.
                        return true;
                    }
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Nullable
        @Override
        public InputRow nextRow() {
            if (nextRow == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return nextRow;
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:org.apache.pig.piggybank.squeal.metrics.RMQMetricsTransport.java

License:Apache License

private void runListener(String queueName, final OutputStream os) throws Exception {
    if (queueName != null) {
        channel.queueDeclare(queueName, true, false, false, null);
    } else {/*from w w  w  .  ja va2  s  .  c o m*/
        queueName = channel.queueDeclare().getQueue();
    }

    channel.queueBind(queueName, exchangeName, "");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, false, consumer);
    int c = 0;

    while (true) {
        Delivery d = consumer.nextDelivery(5000);
        c += 1;
        if (d != null) {
            os.write(d.getBody());
            channel.basicAck(d.getEnvelope().getDeliveryTag(), true);
        }
        if (d == null || c > 1000) {
            os.flush();
            c = 0;
        }
    }
}

From source file:org.apache.pig.piggybank.squeal.spout.RMQSpout.java

License:Apache License

public void nextTuple() {
    try {//www  .j av a  2 s.c om
        Delivery d = consumer.nextDelivery(0);
        if (d != null) {
            long tag = d.getEnvelope().getDeliveryTag();
            int an_id = r.nextInt();
            out_id.put(an_id, tag);
            collector.emit(new Values(d.getBody()), an_id);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.apache.spark.streaming.rabbitmq.JavaRabbitMQConsumer.java

License:Apache License

public static void main(String[] args) throws InterruptedException {

    SparkConf sparkConf = new SparkConf().setAppName("JavaRabbitMQConsumer").setMaster("local[2]");
    JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(10000));
    Map<String, String> params = new HashMap<String, String>();

    params.put("hosts", "localhost");
    params.put("queueName", "rabbitmq-queue");
    params.put("exchangeName", "rabbitmq-exchange");
    params.put("vHost", "/");
    params.put("userName", "guest");
    params.put("password", "guest");

    Function<Delivery, String> messageHandler = new Function<Delivery, String>() {

        public String call(Delivery message) {
            return new String(message.getBody());
        }//w  w  w. j  a  v a 2 s  .  co  m
    };

    JavaReceiverInputDStream<String> messages = RabbitMQUtils.createJavaStream(jssc, String.class, params,
            messageHandler);

    messages.print();

    jssc.start();
    jssc.awaitTermination();
}

From source file:org.apache.spark.streaming.rabbitmq.JavaRabbitMQDistributedConsumer.java

License:Apache License

public static void main(String[] args) throws InterruptedException {

    SparkConf sparkConf = new SparkConf().setAppName("JavaRabbitMQConsumer").setMaster("local[2]");
    JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(10000));
    java.util.Map<String, String> params = new HashMap<String, String>();
    List<JavaRabbitMQDistributedKey> distributedKeys = new LinkedList<JavaRabbitMQDistributedKey>();

    params.put("hosts", "localhost");
    params.put("vHost", "/");
    params.put("userName", "guest");
    params.put("password", "guest");

    distributedKeys.add(new JavaRabbitMQDistributedKey("rabbitmq-queue",
            new ExchangeAndRouting("rabbitmq-exchange"), params));

    Function<Delivery, String> messageHandler = new Function<Delivery, String>() {

        public String call(Delivery message) {
            return new String(message.getBody());
        }/*from  www .  jav a  2 s .co m*/
    };

    JavaInputDStream<String> messages = RabbitMQUtils.createJavaDistributedStream(jssc, String.class,
            distributedKeys, params, messageHandler);

    messages.print();

    jssc.start();
    jssc.awaitTermination();
}

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