Example usage for org.springframework.amqp.support.converter MessageConversionException MessageConversionException

List of usage examples for org.springframework.amqp.support.converter MessageConversionException MessageConversionException

Introduction

In this page you can find the example usage for org.springframework.amqp.support.converter MessageConversionException MessageConversionException.

Prototype

public MessageConversionException(String message) 

Source Link

Usage

From source file:com.jbrisbin.vpc.jobsched.exe.ExeMessageConverter.java

public Message toMessage(Object object, MessageProperties props) throws MessageConversionException {
    if (object instanceof ExeMessage) {
        ExeMessage msg = (ExeMessage) object;
        return new Message(msg.getOutputBytes(), props);
    } else {/*from  w w w.j  av a 2s.com*/
        throw new MessageConversionException(
                "Cannot convert object " + String.valueOf(object) + " using " + getClass().toString());
    }
}

From source file:amqp.spring.converter.ContentTypeConverterFactory.java

@Override
protected Message createMessage(Object object, MessageProperties messageProperties) {
    String contentType = messageProperties.getContentType();
    MessageConverter converter = converters.get(contentType);
    if (converter == null) //Try to fall back
        converter = this.fallbackConverter;
    if (converter == null) //Can't even fall back, punt
        throw new MessageConversionException("Cannot find converter for content type of " + contentType);

    return converter.toMessage(object, messageProperties);
}

From source file:amqp.spring.converter.StringConverter.java

@Override
public Object fromMessage(Message message) throws MessageConversionException {
    MessageProperties messageProperties = message.getMessageProperties();
    if (messageProperties == null)
        throw new MessageConversionException("Cannot decode a message with no properties!");

    byte[] body = message.getBody();
    if (body == null)
        return null;

    String messageEncoding = messageProperties.getContentEncoding();
    if (messageEncoding == null)
        messageEncoding = this.encoding;

    String messageContentType = messageProperties.getContentType();
    if (this.contentType != null && !this.contentType.equalsIgnoreCase(messageContentType))
        throw new MessageConversionException("Cannot understand a message of type " + messageContentType);

    try {/*from  w  w  w.j  av a2 s .co m*/
        return new String(body, messageEncoding);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Cannot dencode strings as {}", this.encoding, ex);
        throw new MessageConversionException("Cannot dencode strings as " + this.encoding, ex);
    }
}

From source file:amqp.spring.converter.ContentTypeConverterFactory.java

@Override
public Object fromMessage(Message message) throws MessageConversionException {
    MessageProperties messageProperties = message.getMessageProperties();
    String contentType = messageProperties.getContentType();
    if (messageProperties == null)
        throw new MessageConversionException("Cannot decode a message with no properties!");

    MessageConverter converter = converters.get(contentType);
    if (converter == null) //Try to fall back
        converter = this.fallbackConverter;
    if (converter == null) //Can't even fall back, punt
        throw new MessageConversionException("Cannot find converter for content type of " + contentType);

    return converter.fromMessage(message);
}

From source file:amqp.spring.converter.XStreamConverter.java

@Override
public Object fromMessage(Message message) throws MessageConversionException {
    MessageProperties messageProperties = message.getMessageProperties();
    if (messageProperties == null)
        throw new MessageConversionException("Cannot decode a message with no properties!");

    byte[] body = message.getBody();
    if (body == null)
        return null;

    String messageEncoding = messageProperties.getContentEncoding();
    if (messageEncoding == null)
        messageEncoding = getEncoding();

    String contentType = messageProperties.getContentType();
    if (!MessageProperties.CONTENT_TYPE_JSON.equalsIgnoreCase(contentType))
        throw new MessageConversionException("Cannot understand a message of type " + contentType);

    try {//from w w  w.  j a va2 s . c o m
        ByteArrayInputStream inStream = new ByteArrayInputStream(body);
        StaxReader reader = new StaxReader(new QNameMap(),
                this.inputFactory.createXMLStreamReader(inStream, messageEncoding));
        return this.objectMapper.unmarshal(reader);
    } catch (XMLStreamException ex) {
        String typeId = (String) messageProperties.getHeaders()
                .get(DefaultClassMapper.DEFAULT_CLASSID_FIELD_NAME);
        LOG.error("XMLStreamException trying to unmarshal message of type {}", typeId, ex);
        throw new MessageConversionException("Could not unmarshal message of type " + typeId, ex);
    } catch (XStreamException ex) {
        //For some reason messages appear to be getting eaten at this stage... very nasty when you try to troubleshoot.
        String typeId = (String) messageProperties.getHeaders()
                .get(DefaultClassMapper.DEFAULT_CLASSID_FIELD_NAME);
        LOG.error("XStreamException trying to unmarshal message of type {}", typeId, ex);
        throw new MessageConversionException("Could not unmarshal message of type " + typeId, ex);
    }
}

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

/**
 * Execute the specified listener, committing or rolling back the transaction afterwards (if necessary).
 *
 * @param channel the Rabbit Channel to operate on
 * @param messageIn the received Rabbit Message
 * @throws Exception Any Exception.//from ww  w .  j a  v  a2 s .co  m
 *
 * @see #invokeListener
 * @see #handleListenerException
 */
protected void executeListener(Channel channel, Message messageIn) throws Exception {
    if (!isRunning()) {
        if (logger.isWarnEnabled()) {
            logger.warn(
                    "Rejecting received message because the listener container has been stopped: " + messageIn);
        }
        throw new MessageRejectedWhileStoppingException();
    }
    try {
        Message message = messageIn;
        if (this.afterReceivePostProcessors != null) {
            for (MessagePostProcessor processor : this.afterReceivePostProcessors) {
                message = processor.postProcessMessage(message);
            }
        }
        Object batchFormat = message.getMessageProperties().getHeaders()
                .get(MessageProperties.SPRING_BATCH_FORMAT);
        if (MessageProperties.BATCH_FORMAT_LENGTH_HEADER4.equals(batchFormat) && this.deBatchingEnabled) {
            ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBody());
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.getHeaders().remove(MessageProperties.SPRING_BATCH_FORMAT);
            while (byteBuffer.hasRemaining()) {
                int length = byteBuffer.getInt();
                if (length < 0 || length > byteBuffer.remaining()) {
                    throw new ListenerExecutionFailedException("Bad batched message received",
                            new MessageConversionException(
                                    "Insufficient batch data at offset " + byteBuffer.position()),
                            message);
                }
                byte[] body = new byte[length];
                byteBuffer.get(body);
                messageProperties.setContentLength(length);
                // Caveat - shared MessageProperties.
                Message fragment = new Message(body, messageProperties);
                invokeListener(channel, fragment);
            }
        } else {
            invokeListener(channel, message);
        }
    } catch (Exception ex) {
        if (messageIn.getMessageProperties().isFinalRetryForMessageWithNoId()) {
            if (this.statefulRetryFatalWithNullMessageId) {
                throw new FatalListenerExecutionException(
                        "Illegal null id in message. Failed to manage retry for message: " + messageIn);
            } else {
                throw new ListenerExecutionFailedException("Cannot retry message more than once without an ID",
                        new AmqpRejectAndDontRequeueException("Not retryable; rejecting and not requeuing", ex),
                        messageIn);
            }
        }
        handleListenerException(ex);
        throw ex;
    }
}

From source file:org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.java

/**
 * Build a Rabbit message to be sent as response based on the given result object.
 * @param channel the Rabbit Channel to operate on
 * @param result the content of the message, as returned from the listener method
 * @return the Rabbit <code>Message</code> (never <code>null</code>)
 * @throws Exception if thrown by Rabbit API methods
 * @see #setMessageConverter/*from  w ww. jav  a2 s  . c  o  m*/
 */
protected Message buildMessage(Channel channel, Object result) throws Exception {
    MessageConverter converter = getMessageConverter();
    if (converter != null && !(result instanceof Message)) {
        return converter.toMessage(result, new MessageProperties());
    } else {
        if (!(result instanceof Message)) {
            throw new MessageConversionException(
                    "No MessageConverter specified - cannot handle message [" + result + "]");
        }
        return (Message) result;
    }
}

From source file:org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.java

/**
 * Build a Rabbit message to be sent as response based on the given result object.
 * @param session the Rabbit Channel to operate on
 * @param result the content of the message, as returned from the listener method
 * @return the Rabbit <code>Message</code> (never <code>null</code>)
 * @throws Exception if thrown by Rabbit API methods
 * @see #setMessageConverter/*from www.j a v a  2  s  .co  m*/
 */
protected Message buildMessage(Channel session, Object result) throws Exception {
    MessageConverter converter = getMessageConverter();
    if (converter != null) {
        return converter.toMessage(result, new MessageProperties());
    } else {
        if (!(result instanceof Message)) {
            throw new MessageConversionException(
                    "No MessageConverter specified - cannot handle message [" + result + "]");
        }
        return (Message) result;
    }
}

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

@Test
public void testErrorHandler() throws Exception {
    brokerRunning.deleteQueues(Q1);//  w  w w. j  a  v a  2s .  c om
    Queue q1 = new Queue(Q1, true, false, false, new ArgumentBuilder().put("x-dead-letter-exchange", "")
            .put("x-dead-letter-routing-key", DLQ1).get());
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    RabbitAdmin admin = new RabbitAdmin(cf);
    admin.declareQueue(q1);
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(Q1);
    container.setConsumersPerQueue(2);
    final AtomicReference<Channel> channel = new AtomicReference<>();
    container.setMessageListener((ChannelAwareMessageListener) (m, c) -> {
        channel.set(c);
        throw new MessageConversionException(
                "intended - should be wrapped in an AmqpRejectAndDontRequeueException");
    });
    container.setBeanName("errorHandler");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate template = new RabbitTemplate(cf);
    template.convertAndSend(Q1, "foo");
    assertNotNull(template.receive(DLQ1, 10000));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    assertFalse(channel.get().isOpen());
    cf.destroy();
}

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

@Test
public void testErrorHandler() throws Exception {
    brokerRunning.getAdmin().deleteQueue(Q1);
    Queue q1 = new Queue(Q1, true, false, false, new ArgumentBuilder().put("x-dead-letter-exchange", "")
            .put("x-dead-letter-routing-key", DLQ1).get());
    brokerRunning.getAdmin().declareQueue(q1);
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(Q1);//ww w  .  j a v a2  s  .c  om
    container.setConsumersPerQueue(2);
    final AtomicReference<Channel> channel = new AtomicReference<>();
    container.setMessageListener((ChannelAwareMessageListener) (m, c) -> {
        channel.set(c);
        throw new MessageConversionException(
                "intended - should be wrapped in an AmqpRejectAndDontRequeueException");
    });
    container.setBeanName("errorHandler");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    RabbitTemplate template = new RabbitTemplate(cf);
    template.convertAndSend(Q1, "foo");
    assertNotNull(template.receive(DLQ1, 10000));
    container.stop();
    assertTrue(consumersOnQueue(Q1, 0));
    assertTrue(consumersOnQueue(Q2, 0));
    assertTrue(activeConsumerCount(container, 0));
    assertEquals(0, TestUtils.getPropertyValue(container, "consumersByQueue", MultiValueMap.class).size());
    assertFalse(channel.get().isOpen());
    cf.destroy();
}