Example usage for com.rabbitmq.client GetResponse getBody

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

Introduction

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

Prototype

public byte[] getBody() 

Source Link

Document

Get the message body included in this response

Usage

From source file:client.RabbitMQConsumerClient.java

License:Open Source License

public List<String> popAllMessages() throws IOException, InterruptedException {
    List<String> messages = new ArrayList<String>();
    GetResponse response;

    while ((response = channel.basicGet(routeKey, true)) != null) {
        messages.add(new String(response.getBody()));
    }/*w  w  w  .j  av a2 s.com*/
    return messages;
}

From source file:com.github.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java

License:Apache License

@Override
public AsyncExecutionRequest getTask() throws AsyncTaskConsumptionException {
    try {//from   ww  w.j a  v  a 2  s.co m
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        GetResponse response = channel.basicGet(this.queue, false);
        if (response != null) {
            AsyncExecutionRequest message = deserialize(response.getBody());

            long deliveryTag = response.getEnvelope().getDeliveryTag();
            channel.basicAck(deliveryTag, true);

            return message;
        }
    } catch (IOException | TimeoutException | ClassNotFoundException ex) {
        LOGGER.error("Failed to read message from the queue", ex);
        throw new AsyncTaskConsumptionException();
    }

    return null; // Won't ever reach here
}

From source file:com.hp.ov.sdk.messaging.msmb.services.MsmbProcessor.java

License:Apache License

@Override
public void run() {

    try {/*from  w  w  w.j  av  a 2 s .co m*/
        // do not specify queue name. AMQP will create a queue with random
        // name starting with amq.gen* e.g. amq.gen-32sfQz9
        final DeclareOk queue = channel.queueDeclare("", true, false, true, null);

        // Now get the queue name from above call and bind it to required
        // Exchange with required routing key.
        channel.queueBind(queue.getQueue(), SdkConstants.MSMB_EXCHANGE_NAME, routingKey);
        // Now you should be able to receive messages from queue
        while (true) {
            final GetResponse chResponse = channel.basicGet(queue.getQueue(), false);
            if (chResponse == null) {
                // LOGGER.debug("ScmbProcessor : run : No Message Received: ");
            } else {
                final byte[] body = chResponse.getBody();
                final String responseBody = new String(body);
                messageQueue.add(responseBody);

            }
            Thread.sleep(5000);
        }
    } catch (final IOException | InterruptedException e) {
        LOGGER.error(
                "ScmbProcessor : run : error in scmb processor : thread might have been interrupted by Stop user");
    }
}

From source file:com.hp.ov.sdk.messaging.scmb.services.ScmbProcessor.java

License:Apache License

@Override
public void run() {

    try {//from   w  w  w . ja  v a  2s .  com
        // do not specify queue name. AMQP will create a queue with random
        // name starting with amq.gen* e.g. amq.gen-32sfQz9
        final DeclareOk queue = channel.queueDeclare("", true, false, true, null);

        // Now get the queue name from above call and bind it to required
        // Exchange with required routing key.
        channel.queueBind(queue.getQueue(), SdkConstants.SCMB_EXCHANGE_NAME, routingKey);
        // Now you should be able to receive messages from queue
        while (true) {
            final GetResponse chResponse = channel.basicGet(queue.getQueue(), false);
            if (chResponse == null) {
                // LOGGER.debug("ScmbProcessor : run : No Message Received: ");
            } else {
                final byte[] body = chResponse.getBody();
                final String responseBody = new String(body);
                messageQueue.add(responseBody);
            }
            Thread.sleep(5000);
        }
    } catch (final IOException | InterruptedException e) {
        LOGGER.error(
                "ScmbProcessor : run : error in scmb processor : thread might have been interrupted by Stop user");
    }
}

From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java

License:Apache License

private Message buildMessageFromResponse(GetResponse response) {
    MessageProperties messageProps = this.messagePropertiesConverter.toMessageProperties(response.getProps(),
            response.getEnvelope(), this.encoding);
    messageProps.setMessageCount(response.getMessageCount());
    return new Message(response.getBody(), messageProps);
}

From source file:com.navercorp.test.pinpoint.plugin.rabbitmq.TestMessagePuller.java

License:Apache License

public <T> T pullMessage(MessageConverter<T> messageConverter, String queueName, boolean autoAck)
        throws IOException {
    GetResponse response = channel.basicGet(queueName, autoAck);
    if (response == null) {
        return null;
    }//from  w w  w  .ja v  a2 s  .c  o  m
    propagationMarker.mark();
    byte[] body = response.getBody();
    T message = messageConverter.convertMessage(body);
    if (!autoAck) {
        channel.basicAck(response.getEnvelope().getDeliveryTag(), false);
    }
    return message;
}

From source file:com.nifi.processors.amqp.ConsumeAMQP.java

License:Apache License

/**
 * Will construct a {@link FlowFile} containing the body of the consumed
 * AMQP message (if {@link GetResponse} returned by {@link AMQPConsumer} is
 * not null) and AMQP properties that came with message which are added to a
 * {@link FlowFile} as attributes, transferring {@link FlowFile} to
 * 'success' {@link Relationship}.//from ww  w.  j ava 2 s. c  o  m
 */
@Override
protected void rendezvousWithAmqp(ProcessContext context, ProcessSession processSession)
        throws ProcessException {
    final GetResponse response = this.targetResource.consume();
    if (response != null) {
        FlowFile flowFile = processSession.create();
        flowFile = processSession.write(flowFile, new OutputStreamCallback() {
            @Override
            public void process(final OutputStream out) throws IOException {
                out.write(response.getBody());
            }
        });
        BasicProperties amqpProperties = response.getProps();
        flowFile = AMQPUtils.updateFlowFileAttributesWithAmqpProperties(amqpProperties, flowFile,
                processSession);
        processSession.getProvenanceReporter().receive(flowFile,
                this.amqpConnection.toString() + "/" + context.getProperty(QUEUE).getValue());
        processSession.transfer(flowFile, REL_SUCCESS);
    } else {
        context.yield();
    }
}

From source file:coyote.dx.reader.RabbitReader.java

License:Open Source License

/**
 * @see coyote.dx.FrameReader#read(coyote.dx.context.TransactionContext)
 *//* w  w w . j av a  2 s  . c o m*/
@Override
public DataFrame read(TransactionContext context) {
    DataFrame retval = null;
    try {
        while (retval == null) {
            GetResponse response = channel.basicGet(getQueueName(), NO_AUTO_ACK);
            if (response != null) {
                byte[] data = null;
                try {
                    data = response.getBody();
                    channel.basicAck(response.getEnvelope().getDeliveryTag(), false);
                } catch (IOException e) {
                    Log.error("Could not get data from message body: " + e.getClass().getName() + " - "
                            + e.getMessage());
                }
                if (data != null) {
                    try {
                        retval = new DataFrame(data);
                    } catch (Exception e) {
                        Log.debug("Received data not in dataframe wire format");
                        String text = StringUtil.getString(data);
                        try {
                            List<DataFrame> frames = JSONMarshaler.marshal(text);
                            if (frames != null && frames.size() > 0) {
                                retval = frames.get(0);
                            } else {
                                Log.notice("Received an empty JSON message");
                            }
                        } catch (MarshalException e1) {
                            Log.debug("Received data not in JSON format");
                            try {
                                List<DataFrame> frames = XMLMarshaler.marshal(text);
                                if (frames != null && frames.size() > 0) {
                                    retval = frames.get(0);
                                } else {
                                    Log.notice("Received an empty XML message");
                                }
                            } catch (MarshalException e2) {
                                Log.error("Could not parse the data received from " + channel.toString());
                            }
                        }
                    }
                } else {
                    Log.warn("Retrieved an empty body from a message: "
                            + response.getEnvelope().getDeliveryTag());
                }
            } else {
                // If we are not in listen mode, break out of the loop and return null, otherwise loop
                if (!isListening()) {
                    break;
                }
            }
        }
    } catch (IOException e) {
        Log.warn("Exception on message retrieval: " + e.getClass().getName() + " - " + e.getMessage());
    }
    return retval;
}

From source file:io.bootique.rabbitmq.client.integration.RabbitMQNamingIT.java

License:Apache License

public void init() throws IOException, TimeoutException {
    try (Connection connection = connectionFactory.forName(CONNECTION_NAME);
            Channel channel = channelFactory.openChannel(connection, EXCHANGE_NAME, QUEUE_NAME, "")) {
        // RabbitMQ Exchange with "bqQueue" must exist or IOException is thrown
        byte[] message = "Hello World!".getBytes("UTF-8");
        channel.basicPublish("", QUEUE_NAME, null, message);
        GetResponse getResponse = channel.basicGet(QUEUE_NAME, false);

        assertEquals(new String(message), new String(getResponse.getBody()));
    }/*from  w w w.j  a v  a 2 s .  c o m*/
}

From source file:io.opentracing.contrib.rabbitmq.TracingTest.java

License:Apache License

@Test
public void basicGet() throws Exception {
    String exchangeName = "basicGetExchange";
    String queueName = "basicGetQueue";
    String routingKey = "#";

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = "Hello, world!".getBytes();

    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    GetResponse response = channel.basicGet(queueName, false);
    assertNotNull(response.getBody());

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(2, finishedSpans.size());
    checkSpans(finishedSpans);//from  ww w  .  j  a v  a 2s  . com

    assertNull(mockTracer.activeSpan());
}