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:org.hobbit.core.rabbit.SimpleFileReceiver.java

License:Open Source License

public String[] receiveData(String outputDirectory)
        throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
    if (!outputDirectory.endsWith(File.separator)) {
        outputDirectory = outputDirectory + File.separator;
    }/*ww  w  .j av  a2  s  . co m*/
    File outDir = new File(outputDirectory);
    if (!outDir.exists()) {
        if (!outDir.mkdirs()) {
            throw new IOException("Couldn't create \"" + outDir.getAbsolutePath() + "\".");
        }
    }
    try {
        Delivery delivery = null;
        // while the receiver should not terminate, the last delivery was
        // not empty or there are still deliveries in the (servers) queue
        while ((!terminated) || (delivery != null) || (queue.channel.messageCount(queue.name) > 0)) {
            delivery = consumer.nextDelivery(waitingForMsgTimeout);
            if (delivery != null) {
                executor.execute(new MessageProcessing(this, outputDirectory, delivery.getBody()));
            }
        }
    } finally {
        close();
    }
    return fileStates.keySet().toArray(new String[fileStates.size()]);
}

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

License:Open Source License

protected void dispatchTestMessageAndAssertValidReceivedMessage(final String flowName) throws Exception {
    final String customHeaderValue = UUID.getUUID();
    final String payload = RandomStringUtils.randomAlphanumeric(20);
    new MuleClient(muleContext).dispatch("vm://" + flowName + ".in", payload,
            Collections.singletonMap("customHeader", customHeaderValue));

    final Delivery dispatchedMessage = consumeMessageWithAmqp(getQueueName(flowName),
            getTestTimeoutSecs() * 1000L);

    assertNotNull(dispatchedMessage);/*from   w ww  .jav a 2s .c  om*/
    assertEquals(payload, new String(dispatchedMessage.getBody()));
    assertEquals(customHeaderValue,
            dispatchedMessage.getProperties().getHeaders().get("customHeader").toString());
}

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

License:Open Source License

private void dispatchTestMessageAndAssertValidReceivedMessage(final String flowName,
        final String targetQueueName) throws Exception {
    final String payload = RandomStringUtils.randomAlphanumeric(20);
    final String correlationId = publishMessageWithAmqp(payload.getBytes(), flowName);

    final Delivery dispatchedMessage = consumeMessageWithAmqp(targetQueueName,
            DEFAULT_MULE_TEST_TIMEOUT_SECS * 1000L);

    assertNotNull(dispatchedMessage);//  w  ww .ja v  a  2 s .  co  m
    assertEquals(payload, new String(dispatchedMessage.getBody()));
    assertEquals(correlationId, dispatchedMessage.getProperties().getCorrelationId());
}

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

License:Open Source License

private void sendTestMessageAndAssertValidReceivedMessage(final String flowName) throws Exception {
    final String payload = RandomStringUtils.randomAlphanumeric(20);
    final String correlationId = UUID.getUUID();

    final Delivery result = sendMessageWithAmqp(correlationId, payload.getBytes(), flowName,
            DEFAULT_MULE_TEST_TIMEOUT_SECS * 1000L);

    assertNotNull(result);/*w  ww  .j a v a2  s.  c o m*/
    assertEquals(payload + "-response", new String(result.getBody()));
    assertEquals(correlationId, result.getProperties().getCorrelationId());
}

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

License:Open Source License

public AmqpMessage consume(final Channel channel, final String queue, final boolean autoAck, final long timeout)
        throws IOException, InterruptedException {
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    final String consumerTag = channel.basicConsume(queue, autoAck, consumer);
    final Delivery delivery = consumer.nextDelivery(timeout);
    channel.basicCancel(consumerTag);// w  w w . ja v  a 2 s .  c om

    if (delivery == null)
        return null;

    return new AmqpMessage(consumerTag, delivery.getEnvelope(), delivery.getProperties(), delivery.getBody());
}

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

License:Open Source License

private void dispatchTestMessageAndAssertValidReceivedMessage(final String flowName) throws Exception {
    final String customHeaderValue = UUID.getUUID();
    final String payload = RandomStringUtils.randomAlphanumeric(20);
    new MuleClient(muleContext).dispatch("vm://" + flowName + ".in", payload,
            Collections.singletonMap("customHeader", customHeaderValue));

    final Delivery dispatchedMessage = consumeMessageWithAmqp(getQueueName(flowName),
            DEFAULT_MULE_TEST_TIMEOUT_SECS * 1000L);

    assertNotNull(dispatchedMessage);//from  w w  w.  j a  va2  s  .  c  o m
    assertEquals(payload, new String(dispatchedMessage.getBody()));
    assertEquals(customHeaderValue,
            dispatchedMessage.getProperties().getHeaders().get("customHeader").toString());
}

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

License:Open Source License

private void dispatchTestMessageAndAssertValidReceivedMessage(String targetQueueName, String exchangeName)
        throws Exception {
    String payload = RandomStringUtils.randomAlphanumeric(20);
    String correlationId = amqpTestClient.publishMessageWithAmqp(payload.getBytes(), exchangeName);

    Delivery dispatchedMessage = amqpTestClient.consumeMessageWithAmqp(targetQueueName,
            getTestTimeoutSecs() * 1000L);

    assertThat(dispatchedMessage, is(notNullValue()));
    assertThat(new String(dispatchedMessage.getBody()), equalTo(payload));
    assertThat(new String(dispatchedMessage.getProperties().getCorrelationId()), equalTo(correlationId));
}

From source file:org.mule.transport.amqp.harness.VmTestClient.java

License:Open Source License

public void fetchAndValidateAmqpDeliveredMessage(String amqpQueueName, int timeoutInSeconds,
        String expectedPayload, String expectedCustomHeaderValue) throws IOException, InterruptedException {
    Delivery dispatchedMessage = amqpTestClient.consumeMessageWithAmqp(amqpQueueName, timeoutInSeconds * 1000L);

    assertThat(dispatchedMessage, is(notNullValue()));

    validateAmqpDeliveredMessage(expectedPayload, expectedCustomHeaderValue, dispatchedMessage.getBody(),
            dispatchedMessage.getProperties());
}

From source file:org.objectweb.proactive.extensions.amqp.remoteobject.AbstractAMQPRemoteObject.java

License:Open Source License

@Override
public final Reply receiveMessage(Request message) throws IOException, ProActiveException {
    RpcReusableChannel channel = getRpcReusableChannel();
    try {/*  w  w  w .ja  va  2s  .  c o m*/
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("AMQP RO sending %s to %s, on exchange %s, queue %s",
                    message.getMethodName(), remoteObjectURL, rpcExchangeName, queueName));
        }

        String replyQueue = channel.getReplyQueue();
        byte[] messageBody = ObjectToByteConverter.ProActiveObjectStream.convert(message);
        channel.getChannel().basicPublish(rpcExchangeName, queueName,
                new BasicProperties.Builder().replyTo(replyQueue).build(), messageBody);

        while (true) {
            Delivery delivery = channel.getReplyQueueConsumer().nextDelivery(replyTimeout);
            if (delivery != null) {
                Reply reply = (Reply) ByteToObjectConverter.ProActiveObjectStream.convert(delivery.getBody());
                if (logger.isDebugEnabled()) {
                    logger.debug(String.format(
                            "AMQP RO received response of message %s to %s, on exchange %s, queue %s",
                            message.getMethodName(), remoteObjectURL, rpcExchangeName, queueName));
                }
                channel.returnChannel();
                return reply;
            } else {
                // if didn't receive reply after timeout expired then check that remote object server still exists
                checkTargetObjectExists();
            }
        }
    } catch (Throwable e) {
        channel.close();

        throw new IOException(String.format("AMQP cannot send %s to %s, on exchange %s, queue %s",
                message.getMethodName(), remoteObjectURL, rpcExchangeName, queueName), e);
    }
}

From source file:org.openbaton.plugin.utils.PluginCaller.java

License:Apache License

public Serializable executeRPC(String methodName, Collection<Serializable> args, Type returnType)
        throws IOException, InterruptedException, PluginException {

    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    String exchange = "plugin-exchange";
    channel.queueBind(replyQueueName, exchange, replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    String consumerTag = channel.basicConsume(replyQueueName, true, consumer);

    //Check if plugin is still up
    if (!RabbitManager.getQueues(brokerIp, username, password, managementPort).contains(pluginId))
        throw new PluginException("Plugin with id: " + pluginId + " not existing anymore...");

    String response;/*from w  ww . ja v a  2s  .com*/
    String corrId = UUID.randomUUID().toString();
    PluginMessage pluginMessage = new PluginMessage();
    pluginMessage.setMethodName(methodName);
    pluginMessage.setParameters(args);
    String message = gson.toJson(pluginMessage);

    BasicProperties props = new Builder().correlationId(corrId).replyTo(replyQueueName).build();

    channel.basicPublish(exchange, pluginId, props, message.getBytes());

    if (returnType != null) {

        while (true) {
            Delivery delivery = consumer.nextDelivery();
            if (delivery.getProperties().getCorrelationId().equals(corrId)) {
                response = new String(delivery.getBody());
                log.trace("received: " + response);
                break;
            } else {
                log.error("Received Message with wrong correlation id");
                throw new PluginException(
                        "Received Message with wrong correlation id. This should not happen, if it does please call us.");
            }
        }

        channel.queueDelete(replyQueueName);
        try {
            channel.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);

        JsonElement exceptionJson = jsonObject.get("exception");
        if (exceptionJson == null) {
            JsonElement answerJson = jsonObject.get("answer");

            Serializable ret = null;

            if (answerJson.isJsonPrimitive()) {
                ret = gson.fromJson(answerJson.getAsJsonPrimitive(), returnType);
            } else if (answerJson.isJsonArray()) {
                ret = gson.fromJson(answerJson.getAsJsonArray(), returnType);
            } else
                ret = gson.fromJson(answerJson.getAsJsonObject(), returnType);

            log.trace("answer is: " + ret);
            return ret;
        } else {
            PluginException pluginException;
            try {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), VimDriverException.class));
                log.debug("Got Vim Driver Exception with server: "
                        + ((VimDriverException) pluginException.getCause()).getServer());
            } catch (Exception ignored) {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), Throwable.class));
            }
            throw pluginException;
        }
    } else
        return null;
}