Example usage for org.springframework.amqp.core MessageProperties setHeader

List of usage examples for org.springframework.amqp.core MessageProperties setHeader

Introduction

In this page you can find the example usage for org.springframework.amqp.core MessageProperties setHeader.

Prototype

public void setHeader(String key, Object value) 

Source Link

Usage

From source file:amqp.spring.camel.component.SpringAMQPHeaderTest.java

@Test
public void copyAMQPHeaders() throws Exception {
    MessageProperties properties = new MessageProperties();
    properties.setHeader("NotSecret", "Popcorn");
    org.springframework.amqp.core.Message message = new Message(new byte[] {}, properties);
    message.getMessageProperties().setReplyTo("BuzzSaw");

    SpringAMQPMessage camelMessage = SpringAMQPHeader.copyHeaders(new SpringAMQPMessage(),
            message.getMessageProperties().getHeaders());
    Assert.assertEquals("Popcorn", camelMessage.getHeader("NotSecret"));
    Assert.assertNull(camelMessage.getHeader(SpringAMQPHeader.REPLY_TO));
}

From source file:amqp.spring.camel.component.SpringAMQPHeaderTest.java

@Test
public void fromBasicProperties() throws Exception {
    MessageProperties properties = new MessageProperties();
    properties.setHeader("NotSecret", "Popcorn");
    org.springframework.amqp.core.Message message = new Message(new byte[] {}, properties);
    message.getMessageProperties().setPriority(1);
    message.getMessageProperties().setReplyTo("BuzzSaw");

    SpringAMQPMessage camelMessage = SpringAMQPHeader.setBasicPropertiesToHeaders(new SpringAMQPMessage(),
            message);/* w ww .j a va  2s .  co  m*/
    Assert.assertNull(camelMessage.getHeader("NotSecret"));
    Assert.assertEquals(1, camelMessage.getHeader(SpringAMQPHeader.PRIORITY));
    Assert.assertEquals("BuzzSaw", camelMessage.getHeader(SpringAMQPHeader.REPLY_TO));
}

From source file:amqp.spring.camel.component.SpringAMQPMessageTest.java

@Test
public void fromAMQP() throws Exception {
    String body = "Test Message";
    MessageConverter msgConverter = new StringMessageConverter();
    MessageProperties properties = new MessageProperties();
    properties.setHeader("NotSecret", "Popcorn");
    org.springframework.amqp.core.Message message = new org.springframework.amqp.core.Message(body.getBytes(),
            properties);//from  w ww . j av  a2  s  . c  o m

    SpringAMQPMessage camelMessage = SpringAMQPMessage.fromAMQPMessage(msgConverter, message);
    Assert.assertEquals(body, camelMessage.getBody(String.class));
    Assert.assertEquals("Popcorn", camelMessage.getHeader("NotSecret"));
}

From source file:org.carewebframework.amqp.rabbitmq.Broker.java

/**
 * Given a Message, supplement the message with additional properties/attributes ( recipients,
 * sender)./* w w  w . j  a  v a  2 s . c  o m*/
 * 
 * @param message The message.
 * @param sender Sender client ID.
 * @param recipients Comma-delimited list of recipient client IDs.
 * @return The decorated Message.
 */
private Message decorateMessage(Message message, String sender, String recipients) {
    MessageProperties props = message.getMessageProperties();
    props.setHeader(SENDER_PROPERTY, sender);
    props.setHeader(RECIPIENTS_PROPERTY, recipients);
    return message;
}

From source file:de.davidbilge.spring.remoting.amqp.client.AmqpClientInterceptor.java

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setHeader(Constants.INVOKED_METHOD_HEADER_NAME,
            methodHeaderNamingStrategy.generateMethodName(invocation.getMethod()));

    Message m = getMessageConverter().toMessage(invocation.getArguments(), messageProperties);

    Message resultMessage;/* w  w w .j a va 2s.  c om*/
    if (getRoutingKey() == null) {
        // Use the template's default routing key
        resultMessage = amqpTemplate.sendAndReceive(m);
    } else {
        resultMessage = amqpTemplate.sendAndReceive(getRoutingKey(), m);
    }

    Object result = getMessageConverter().fromMessage(resultMessage);

    if (invocation.getMethod().getReturnType().getCanonicalName().equals(Void.class.getCanonicalName())) {
        return null;
    } else if (result instanceof Throwable
            && !invocation.getMethod().getReturnType().isAssignableFrom(result.getClass())) {
        // TODO handle for case where exceptions that are not known to the
        // caller are being thrown (might be nested unchecked exceptions)
        throw (Throwable) result;
    } else {
        return result;
    }
}

From source file:com.jbrisbin.vpc.jobsched.RequeueJob.java

public void maybeRequeue() {
    RequestMeta meta = new RequestMeta();
    meta.setQueryParam("keys", "true");
    BucketResponse bucket = riak.listBucket(riakBucket, meta);
    if (bucket.isSuccess()) {
        for (String messageId : bucket.getBucketInfo().getKeys()) {
            FetchResponse response = riak.fetch(riakBucket, messageId);
            if (response.isSuccess()) {
                // Try re-queueing message
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Requeueing messageId: " + messageId);
                    }/*from w  ww  .j  a  va 2s  . co m*/
                    final Map<String, Object> message = mapper.readValue(response.getBodyAsString(), Map.class);
                    RabbitTemplate tmpl = appCtx.getBean(RabbitTemplate.class);
                    final MessageProperties props = new RabbitMessageProperties();
                    Map headers = (Map) message.get("headers");
                    for (Object key : headers.keySet()) {
                        props.setHeader(key.toString(), headers.get(key));
                    }
                    props.setCorrelationId(messageId.getBytes());
                    props.setContentType("application/json");
                    tmpl.send(message.get("exchange").toString(), message.get("route").toString(),
                            new MessageCreator() {
                                @Override
                                public Message createMessage() {
                                    Message msg = new Message(message.get("body").toString().getBytes(), props);
                                    if (log.isDebugEnabled()) {
                                        log.debug("Sending AMQP message: " + msg.toString());
                                    }
                                    return msg;
                                }
                            });
                    // Delete from nosql store
                    if (log.isDebugEnabled()) {
                        log.debug("Deleting messageId " + messageId + " from requeue cache");
                    }
                    riak.delete(riakBucket, messageId);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

@SuppressWarnings("unchecked")
private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback,
        final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException {
    return this.execute(new ChannelCallback<Boolean>() {

        @Override/*from   w ww  .  j  av a 2  s . c  o  m*/
        public Boolean doInRabbit(Channel channel) throws Exception {
            boolean channelTransacted = RabbitTemplate.this.isChannelTransacted();

            GetResponse response = channel.basicGet(queueName, !channelTransacted);
            // Response can be null in the case that there is no message on
            // the queue.
            if (response != null) {
                long deliveryTag = response.getEnvelope().getDeliveryTag();
                boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel);

                if (channelLocallyTransacted) {
                    channel.basicAck(deliveryTag, false);
                } else if (channelTransacted) {
                    // Not locally transacted but it is transacted so it
                    // could be synchronized with an external transaction
                    ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(),
                            channel, deliveryTag);
                }

                Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response);

                Object receive = receiveMessage;
                if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) {
                    receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage);
                }

                S reply;
                try {
                    reply = callback.handle((R) receive);
                } catch (ClassCastException e) {
                    StackTraceElement[] trace = e.getStackTrace();
                    if (trace[0].getMethodName().equals("handle")
                            && trace[1].getFileName().equals("RabbitTemplate.java")) {
                        throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback
                                + "' can't handle received object '" + receive + "'", e);
                    } else {
                        throw e;
                    }
                }

                if (reply != null) {
                    Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply);

                    Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply);

                    MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties();
                    MessageProperties replyMessageProperties = replyMessage.getMessageProperties();

                    Object correlation = RabbitTemplate.this.correlationKey == null
                            ? receiveMessageProperties.getCorrelationId()
                            : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey);

                    if (RabbitTemplate.this.correlationKey == null || correlation == null) {
                        // using standard correlationId property
                        if (correlation == null) {
                            String messageId = receiveMessageProperties.getMessageId();
                            if (messageId != null) {
                                correlation = messageId.getBytes(RabbitTemplate.this.encoding);
                            }
                        }
                        replyMessageProperties.setCorrelationId((byte[]) correlation);
                    } else {
                        replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation);
                    }

                    // 'doSend()' takes care about 'channel.txCommit()'.
                    RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(),
                            replyMessage, null);
                } else if (channelLocallyTransacted) {
                    channel.txCommit();
                }

                return true;
            }
            return false;
        }
    });
}

From source file:org.springframework.amqp.rabbit.support.RabbitUtils.java

public static MessageProperties createMessageProperties(final BasicProperties source, final Envelope envelope,
        final String charset) {
    MessageProperties target = new MessageProperties();
    Map<String, Object> headers = source.getHeaders();
    if (!CollectionUtils.isEmpty(headers)) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) {
            target.setHeader(entry.getKey(), entry.getValue());
        }//from  w  w w . j  a  v  a  2s  .  c  om
    }
    target.setTimestamp(source.getTimestamp());
    target.setMessageId(source.getMessageId());
    target.setUserId(source.getUserId());
    target.setAppId(source.getAppId());
    target.setClusterId(source.getClusterId());
    target.setType(source.getType());
    Integer deliverMode = source.getDeliveryMode();
    if (deliverMode != null) {
        target.setDeliveryMode(MessageDeliveryMode.fromInt(deliverMode));
    }
    target.setExpiration(source.getExpiration());
    target.setPriority(source.getPriority());
    target.setContentType(source.getContentType());
    target.setContentEncoding(source.getContentEncoding());
    String correlationId = source.getCorrelationId();
    if (correlationId != null) {
        try {
            target.setCorrelationId(source.getCorrelationId().getBytes(charset));
        } catch (UnsupportedEncodingException ex) {
            throw new AmqpUnsupportedEncodingException(ex);
        }
    }
    String replyTo = source.getReplyTo();
    if (replyTo != null) {
        target.setReplyTo(new Address(replyTo));
    }
    if (envelope != null) {
        target.setReceivedExchange(envelope.getExchange());
        target.setReceivedRoutingKey(envelope.getRoutingKey());
        target.setRedelivered(envelope.isRedeliver());
        target.setDeliveryTag(envelope.getDeliveryTag());
    }
    // TODO: what about messageCount?
    return target;
}

From source file:org.springframework.amqp.support.postprocessor.AbstractCompressingPostProcessor.java

@Override
public Message postProcessMessage(Message message) throws AmqpException {
    ByteArrayOutputStream zipped = new ByteArrayOutputStream();
    try {/*from   w w w . j av a 2s . c o m*/
        OutputStream zipper = getCompressorStream(zipped);
        FileCopyUtils.copy(new ByteArrayInputStream(message.getBody()), zipper);
        MessageProperties messageProperties = message.getMessageProperties();
        String currentEncoding = messageProperties.getContentEncoding();
        messageProperties
                .setContentEncoding(getEncoding() + (currentEncoding == null ? "" : ":" + currentEncoding));
        if (this.autoDecompress) {
            messageProperties.setHeader(MessageProperties.SPRING_AUTO_DECOMPRESS, true);
        }
        byte[] compressed = zipped.toByteArray();
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Compressed " + message.getBody().length + " to " + compressed.length);
        }
        return new Message(compressed, messageProperties);
    } catch (IOException e) {
        throw new AmqpIOException(e);
    }
}