Example usage for com.rabbitmq.client Delivery getProperties

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

Introduction

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

Prototype

public AMQP.BasicProperties getProperties() 

Source Link

Document

Retrieve the message properties.

Usage

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);/*www  . j  av  a2 s  . c  om*/
    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);//  ww  w. j  ava 2 s.co  m

    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);/* w w w  .  j ava 2  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.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;//w ww.j  a  v a2s.  c om
    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;
}

From source file:org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.java

License:Apache License

/**
 * If this is a non-POISON non-null delivery simply return it.
 * If this is POISON we are in shutdown mode, throw
 * shutdown. If delivery is null, we may be in shutdown mode. Check and see.
 * @throws InterruptedException/*ww  w .ja  v a2  s  .  co m*/
 */
private Message handle(Delivery delivery) throws InterruptedException {
    if ((delivery == null && shutdown != null)) {
        throw shutdown;
    }
    if (delivery == null) {
        return null;
    }
    byte[] body = delivery.getBody();
    Envelope envelope = delivery.getEnvelope();

    MessageProperties messageProperties = this.messagePropertiesConverter
            .toMessageProperties(delivery.getProperties(), envelope, "UTF-8");
    messageProperties.setMessageCount(0);
    Message message = new Message(body, messageProperties);
    if (logger.isDebugEnabled()) {
        logger.debug("Received message: " + message);
    }
    deliveryTags.add(messageProperties.getDeliveryTag());
    return message;
}

From source file:org.zenoss.amqp.impl.ConsumerImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private Message<T> createMessage(Delivery delivery) throws AmqpException {
    final T body;
    final byte[] rawBody;
    final MessageProperties properties = new BasicPropertiesWrapper(delivery.getProperties());
    final MessageEnvelope envelope = new EnvelopeWrapper(delivery.getEnvelope());
    if ("deflate".equalsIgnoreCase(properties.getContentEncoding())) {
        try {/* ww w . ja  va 2  s .c  om*/
            rawBody = deflateDecompress(delivery.getBody());
        } catch (IOException e) {
            logger.warn("Failed to decompress message", e);
            // Throw MessageDecoderException so we don't loop attempting to read invalid message
            throw new MessageDecoderException(
                    DefaultMessage.newMessage(delivery.getBody(), properties, envelope), e);
        }
    } else {
        rawBody = delivery.getBody();
    }
    if (converter == null) {
        body = (T) rawBody;
    } else {
        try {
            body = converter.fromBytes(rawBody, properties);
        } catch (Exception e) {
            /* Throw exception with original received message on failure */
            throw new MessageDecoderException(DefaultMessage.newMessage(rawBody, properties, envelope), e);
        }
        /* Throw exception if we failed to convert the message */
        if (body == null) {
            throw new MessageDecoderException(DefaultMessage.newMessage(rawBody, properties, envelope));
        }
    }
    return DefaultMessage.newMessage(body, properties, envelope);
}

From source file:pl.nask.hsn2.DataStoreActiveCleaner.java

License:Open Source License

/**
 * Main loop. Listens for JobFinished and JobFinishedReminder and if one appears it starts job removing tasks.
 *///from   w  ww .j  a  v a2 s  .  c o m
private void listenAndClean() {
    try {
        QueueingConsumer consumer = initRabbitMqConnection();
        LOGGER.info("Waiting for messages...");
        while (true) {
            // Listen for message.
            Delivery delivery = consumer.nextDelivery();
            String type = delivery.getProperties().getType();
            LOGGER.debug("Got delivery {}", type);

            // Clean if job finished data.
            try {
                if ("JobFinished".equals(type)) {
                    JobFinished jobFinishedData = JobFinished.parseFrom(delivery.getBody());
                    startJobDataRemoving(jobFinishedData.getJob(), jobFinishedData.getStatus());
                } else if ("JobFinishedReminder".equals(type)) {
                    JobFinishedReminder jobFinishedData = JobFinishedReminder.parseFrom(delivery.getBody());
                    startJobDataRemoving(jobFinishedData.getJob(), jobFinishedData.getStatus());
                }
            } catch (InvalidProtocolBufferException e) {
                LOGGER.warn("Invalid message! Expected: " + type, e);
            }
        }
    } catch (ShutdownSignalException e) {
        LOGGER.warn("Shutdown signal received.", e);
    } catch (ConsumerCancelledException e) {
        LOGGER.info("Cancell signal received.", e);
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted.", e);
    } catch (IOException e) {
        LOGGER.error("Connection issue.", e);
    }
}

From source file:pl.nask.hsn2.unicorn.connector.ConnectorImpl.java

License:Open Source License

public Response receive() throws ConnectionException {
    try {/*from w  w  w . j  av a 2  s .  c  om*/
        Delivery delivery = consumer.nextDelivery();
        BasicProperties properties = delivery.getProperties();
        return new Response(properties.getType(), properties.getContentType(), delivery.getBody());
    } catch (ShutdownSignalException e) {
        throw new ConnectionException("Receiving error!", e);
    } catch (InterruptedException e) {
        throw new ConnectionException("Receiving error!", e);
    }
}