Search in sources :

Example 11 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class DefaultPahoMessageConverter method messageToMqttBytes.

/**
 * Subclasses can override this method to convert the payload to a byte[].
 * The default implementation accepts a byte[] or String payload.
 * If a {@link BytesMessageMapper} is provided, conversion to byte[]
 * is delegated to it, so any payload that it can handle is supported.
 *
 * @param message The outbound Message.
 * @return The byte[] which will become the payload of the MQTT Message.
 */
protected byte[] messageToMqttBytes(Message<?> message) {
    if (this.bytesMessageMapper != null) {
        try {
            return this.bytesMessageMapper.fromMessage(message);
        } catch (Exception e) {
            throw new MessageHandlingException(message, "Failed to map outbound message", e);
        }
    } else {
        Object payload = message.getPayload();
        Assert.isTrue(payload instanceof byte[] || payload instanceof String, () -> "This default converter can only handle 'byte[]' or 'String' payloads; consider adding a " + "transformer to your flow definition, or provide a BytesMessageMapper, " + "or subclass this converter for " + payload.getClass().getName() + " payloads");
        byte[] payloadBytes;
        if (payload instanceof String) {
            try {
                payloadBytes = ((String) payload).getBytes(this.charset);
            } catch (Exception e) {
                throw new MessageConversionException("failed to convert Message to object", e);
            }
        } else {
            payloadBytes = (byte[]) payload;
        }
        return payloadBytes;
    }
}
Also used : MessageConversionException(org.springframework.messaging.converter.MessageConversionException) MessageConversionException(org.springframework.messaging.converter.MessageConversionException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException)

Example 12 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class ConnectionEventTests method testOutboundChannelAdapterNoConnectionEvents.

@Test
public void testOutboundChannelAdapterNoConnectionEvents() {
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    AbstractServerConnectionFactory scf = new AbstractServerConnectionFactory(0) {

        @Override
        public void run() {
        }
    };
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    scf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }
    });
    handler.setConnectionFactory(scf);
    handler.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar").build();
    try {
        handler.handleMessage(message);
        fail("expected exception");
    } catch (MessageHandlingException e) {
        assertThat(e.getMessage(), Matchers.containsString("Unable to find outbound socket"));
    }
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    assertSame(message, ((MessagingException) event.getCause()).getFailedMessage());
}
Also used : TcpSendingMessageHandler(org.springframework.integration.ip.tcp.TcpSendingMessageHandler) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEvent(org.springframework.context.ApplicationEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test)

Example 13 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class RedisStoreWritingMessageHandler method handleMessageInternal.

/**
 * Will extract the payload from the Message and store it in the collection identified by the
 * key (which may be determined by an expression). The type of collection is specified by the
 * {@link #collectionType} property. The default CollectionType is LIST.
 * <p>
 * The rules for storing the payload are:
 * <p>
 * <b>LIST/SET</b>
 * If the payload is of type Collection and {@link #extractPayloadElements} is 'true' (default),
 * the payload will be added using the addAll() method. If {@link #extractPayloadElements}
 * is set to 'false', then regardless of the payload type, the payload will be added using add().
 * <p>
 * <b>ZSET</b>
 * In addition to the rules described for LIST/SET, ZSET allows 'score' information
 * to be provided. The score can be provided using the {@link RedisHeaders#ZSET_SCORE} message header
 * when the payload is not a Map, or by sending a Map as the payload where each Map 'key' is a
 * value to be saved and each corresponding Map 'value' is the score assigned to it.
 * If {@link #extractPayloadElements} is set to 'false' the map will be stored as a single entry.
 * If the 'score' can not be determined, the default value (1) will be used.
 * <p>
 * <b>MAP/PROPERTIES</b>
 * You can also add items to a Map or Properties based store.
 * If the payload itself is of type Map or Properties, it can be stored either as a batch or single
 * item following the same rules as described above for other collection types.
 * If the payload itself needs to be stored as a value of the map/property then the map key
 * must be specified via the mapKeyExpression (default {@link RedisHeaders#MAP_KEY} Message header).
 */
@SuppressWarnings("unchecked")
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
    String key = this.keyExpression.getValue(this.evaluationContext, message, String.class);
    Assert.hasText(key, () -> "Failed to determine a key for the Redis store based on the message: " + message);
    RedisStore store = this.createStoreView(key);
    Assert.state(this.initialized, "handler not initialized - afterPropertiesSet() must be called before the first use");
    try {
        if (this.collectionType == CollectionType.ZSET) {
            writeToZset((RedisZSet<Object>) store, message);
        } else if (this.collectionType == CollectionType.SET) {
            writeToSet((RedisSet<Object>) store, message);
        } else if (this.collectionType == CollectionType.LIST) {
            writeToList((RedisList<Object>) store, message);
        } else if (this.collectionType == CollectionType.MAP) {
            writeToMap((RedisMap<Object, Object>) store, message);
        } else if (this.collectionType == CollectionType.PROPERTIES) {
            writeToProperties((RedisProperties) store, message);
        }
    } catch (Exception e) {
        throw new MessageHandlingException(message, "Failed to store Message data in Redis collection", e);
    }
}
Also used : RedisSet(org.springframework.data.redis.support.collections.RedisSet) RedisMap(org.springframework.data.redis.support.collections.RedisMap) RedisStore(org.springframework.data.redis.support.collections.RedisStore) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException)

Example 14 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class GroovyServiceActivatorTests method invalidInlineScript.

// INT-2399
@Test(expected = MessageHandlingException.class)
public void invalidInlineScript() throws Exception {
    Message<?> message = new ErrorMessage(new ReplyRequiredException(new GenericMessage<String>("test"), "reply required!"));
    try {
        this.invalidInlineScript.send(message);
        fail("MessageHandlingException expected!");
    } catch (Exception e) {
        Throwable cause = e.getCause();
        assertEquals(MissingPropertyException.class, cause.getClass());
        assertThat(cause.getMessage(), Matchers.containsString("No such property: ReplyRequiredException for class: script"));
        throw e;
    }
}
Also used : GenericMessage(org.springframework.messaging.support.GenericMessage) ReplyRequiredException(org.springframework.integration.handler.ReplyRequiredException) MissingPropertyException(groovy.lang.MissingPropertyException) ErrorMessage(org.springframework.messaging.support.ErrorMessage) ReplyRequiredException(org.springframework.integration.handler.ReplyRequiredException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MissingPropertyException(groovy.lang.MissingPropertyException) BeanDefinitionParsingException(org.springframework.beans.factory.parsing.BeanDefinitionParsingException) Test(org.junit.Test)

Example 15 with MessageHandlingException

use of org.springframework.messaging.MessageHandlingException in project spring-integration by spring-projects.

the class AbstractHttpRequestExecutingMessageHandler method generateUri.

private URI generateUri(Message<?> requestMessage) {
    Object uri = this.uriExpression.getValue(this.evaluationContext, requestMessage);
    Assert.state(uri instanceof String || uri instanceof URI, "'uriExpression' evaluation must result in a 'String' or 'URI' instance, not: " + (uri == null ? "null" : uri.getClass()));
    Map<String, ?> uriVariables = determineUriVariables(requestMessage);
    UriComponentsBuilder uriComponentsBuilder = uri instanceof String ? UriComponentsBuilder.fromUriString((String) uri) : UriComponentsBuilder.fromUri((URI) uri);
    UriComponents uriComponents = uriComponentsBuilder.buildAndExpand(uriVariables);
    try {
        return this.encodeUri ? uriComponents.toUri() : new URI(uriComponents.toUriString());
    } catch (URISyntaxException e) {
        throw new MessageHandlingException(requestMessage, "Invalid URI [" + uri + "]", e);
    }
}
Also used : UriComponents(org.springframework.web.util.UriComponents) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) MessageHandlingException(org.springframework.messaging.MessageHandlingException)

Aggregations

MessageHandlingException (org.springframework.messaging.MessageHandlingException)66 Test (org.junit.Test)34 ErrorMessage (org.springframework.messaging.support.ErrorMessage)14 IOException (java.io.IOException)12 GenericMessage (org.springframework.messaging.support.GenericMessage)12 Message (org.springframework.messaging.Message)10 MessagingException (org.springframework.messaging.MessagingException)10 File (java.io.File)9 Matchers.containsString (org.hamcrest.Matchers.containsString)6 BeanFactory (org.springframework.beans.factory.BeanFactory)6 FileNotFoundException (java.io.FileNotFoundException)4 ArrayList (java.util.ArrayList)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)4 MessageRejectedException (org.springframework.integration.MessageRejectedException)4 QueueChannel (org.springframework.integration.channel.QueueChannel)4 AbstractReplyProducingMessageHandler (org.springframework.integration.handler.AbstractReplyProducingMessageHandler)4 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 IntegrationMessageHeaderAccessor (org.springframework.integration.IntegrationMessageHeaderAccessor)3