Search in sources :

Example 1 with MessageMappingException

use of org.springframework.integration.mapping.MessageMappingException in project spring-integration by spring-projects.

the class MessagingGatewaySupport method doSendAndReceiveMessageReactive.

@SuppressWarnings("unchecked")
private Mono<Message<?>> doSendAndReceiveMessageReactive(MessageChannel requestChannel, Object object, boolean error) {
    return Mono.defer(() -> {
        Message<?> message;
        try {
            message = object instanceof Message<?> ? (Message<?>) object : this.requestMapper.toMessage(object);
            message = this.historyWritingPostProcessor.postProcessMessage(message);
        } catch (Exception e) {
            throw new MessageMappingException("Cannot map to message: " + object, e);
        }
        Object originalReplyChannelHeader = message.getHeaders().getReplyChannel();
        Object originalErrorChannelHeader = message.getHeaders().getErrorChannel();
        FutureReplyChannel replyChannel = new FutureReplyChannel();
        Message<?> requestMessage = MutableMessageBuilder.fromMessage(message).setReplyChannel(replyChannel).setHeader(this.messagingTemplate.getSendTimeoutHeader(), null).setHeader(this.messagingTemplate.getReceiveTimeoutHeader(), null).setErrorChannel(replyChannel).build();
        if (requestChannel instanceof ReactiveStreamsSubscribableChannel) {
            ((ReactiveStreamsSubscribableChannel) requestChannel).subscribeTo(Mono.just(requestMessage));
        } else {
            long sendTimeout = sendTimeout(requestMessage);
            boolean sent = sendTimeout >= 0 ? requestChannel.send(requestMessage, sendTimeout) : requestChannel.send(requestMessage);
            if (!sent) {
                throw new MessageDeliveryException(requestMessage, "Failed to send message to channel '" + requestChannel + "' within timeout: " + sendTimeout);
            }
        }
        return Mono.fromFuture(replyChannel.messageFuture).doOnSubscribe(s -> {
            if (!error && this.countsEnabled) {
                this.messageCount.incrementAndGet();
            }
        }).<Message<?>>map(replyMessage -> MessageBuilder.fromMessage(replyMessage).setHeader(MessageHeaders.REPLY_CHANNEL, originalReplyChannelHeader).setHeader(MessageHeaders.ERROR_CHANNEL, originalErrorChannelHeader).build()).onErrorResume(t -> error ? Mono.error(t) : handleSendError(requestMessage, t));
    });
}
Also used : MessagingException(org.springframework.messaging.MessagingException) AbstractEndpoint(org.springframework.integration.endpoint.AbstractEndpoint) TrackableComponent(org.springframework.integration.support.management.TrackableComponent) IntegrationManagedResource(org.springframework.integration.support.management.IntegrationManagedResource) SubscribableChannel(org.springframework.messaging.SubscribableChannel) CompletableFuture(java.util.concurrent.CompletableFuture) ReactiveStreamsConsumer(org.springframework.integration.endpoint.ReactiveStreamsConsumer) ErrorMessage(org.springframework.messaging.support.ErrorMessage) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) ErrorMessageStrategy(org.springframework.integration.support.ErrorMessageStrategy) MessagingTemplate(org.springframework.integration.core.MessagingTemplate) OutboundMessageMapper(org.springframework.integration.mapping.OutboundMessageMapper) MessageTimeoutException(org.springframework.integration.MessageTimeoutException) EventDrivenConsumer(org.springframework.integration.endpoint.EventDrivenConsumer) Map(java.util.Map) InboundMessageMapper(org.springframework.integration.mapping.InboundMessageMapper) Nullable(org.springframework.lang.Nullable) Message(org.springframework.messaging.Message) PollableChannel(org.springframework.messaging.PollableChannel) Subscriber(org.reactivestreams.Subscriber) HistoryWritingMessagePostProcessor(org.springframework.integration.history.HistoryWritingMessagePostProcessor) DefaultErrorMessageStrategy(org.springframework.integration.support.DefaultErrorMessageStrategy) MessageBuilderFactory(org.springframework.integration.support.MessageBuilderFactory) SimpleMessageConverter(org.springframework.integration.support.converter.SimpleMessageConverter) Mono(reactor.core.publisher.Mono) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) MessageSourceMetrics(org.springframework.integration.support.management.MessageSourceMetrics) MessageChannel(org.springframework.messaging.MessageChannel) MessageHeaders(org.springframework.messaging.MessageHeaders) BridgeHandler(org.springframework.integration.handler.BridgeHandler) AtomicLong(java.util.concurrent.atomic.AtomicLong) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) AttributeAccessor(org.springframework.core.AttributeAccessor) MessageMappingException(org.springframework.integration.mapping.MessageMappingException) ErrorMessageUtils(org.springframework.integration.support.ErrorMessageUtils) MessageBuilder(org.springframework.messaging.support.MessageBuilder) DefaultMessageBuilderFactory(org.springframework.integration.support.DefaultMessageBuilderFactory) MutableMessageBuilder(org.springframework.integration.support.MutableMessageBuilder) Assert(org.springframework.util.Assert) MessageMappingException(org.springframework.integration.mapping.MessageMappingException) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) MessagingException(org.springframework.messaging.MessagingException) MessageTimeoutException(org.springframework.integration.MessageTimeoutException) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) MessageMappingException(org.springframework.integration.mapping.MessageMappingException)

Example 2 with MessageMappingException

use of org.springframework.integration.mapping.MessageMappingException in project spring-integration by spring-projects.

the class DatagramPacketMessageMapperTests method testTruncation.

@Test
public void testTruncation() throws Exception {
    String test = "ABCD";
    Message<byte[]> message = MessageBuilder.withPayload(test.getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    mapper.setAckAddress("localhost:11111");
    mapper.setAcknowledge(false);
    mapper.setLengthCheck(true);
    DatagramPacket packet = mapper.fromMessage(message);
    // Force a truncation failure
    ByteBuffer bb = ByteBuffer.wrap(packet.getData());
    int bigLen = 99999;
    bb.putInt(bigLen);
    packet.setSocketAddress(new InetSocketAddress("localhost", 22222));
    try {
        mapper.toMessage(packet);
        fail("Truncated message exception expected");
    } catch (MessageMappingException e) {
        assertTrue(e.getMessage().contains("expected " + (bigLen + 4) + ", received " + (test.length() + 4)));
    }
}
Also used : MessageMappingException(org.springframework.integration.mapping.MessageMappingException) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(java.net.DatagramPacket) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 3 with MessageMappingException

use of org.springframework.integration.mapping.MessageMappingException in project spring-integration by spring-projects.

the class MailSendingMessageHandler method createMailMessageFromByteArrayMessage.

private MailMessage createMailMessageFromByteArrayMessage(Message<byte[]> message) {
    Assert.state(this.mailSender instanceof JavaMailSender, "this adapter requires a 'JavaMailSender' to send a 'MimeMailMessage'");
    String attachmentFileName = message.getHeaders().get(MailHeaders.ATTACHMENT_FILENAME, String.class);
    if (attachmentFileName == null) {
        throw new MessageMappingException(message, "Header '" + MailHeaders.ATTACHMENT_FILENAME + "' is required when mapping a Message with a byte array payload to a MailMessage.");
    }
    Integer multipartMode = message.getHeaders().get(MailHeaders.MULTIPART_MODE, Integer.class);
    if (multipartMode == null) {
        multipartMode = MimeMessageHelper.MULTIPART_MODE_MIXED;
    }
    MimeMessage mimeMessage = ((JavaMailSender) this.mailSender).createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipartMode);
        helper.addAttachment(attachmentFileName, new ByteArrayResource(message.getPayload()));
        return new MimeMailMessage(helper);
    } catch (MessagingException e) {
        throw new MessageMappingException(message, "failed to create MimeMessage", e);
    }
}
Also used : MessageMappingException(org.springframework.integration.mapping.MessageMappingException) MimeMailMessage(org.springframework.mail.javamail.MimeMailMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) ByteArrayResource(org.springframework.core.io.ByteArrayResource) JavaMailSender(org.springframework.mail.javamail.JavaMailSender) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper)

Example 4 with MessageMappingException

use of org.springframework.integration.mapping.MessageMappingException in project spring-integration by spring-projects.

the class DatagramPacketMessageMapper method startsWith.

/**
 * Peeks at data in the buffer to see if starts with the prefix.
 */
private boolean startsWith(ByteBuffer buffer, String prefix) {
    int pos = buffer.position();
    if (buffer.limit() - pos < prefix.length()) {
        return false;
    }
    try {
        byte[] comparing;
        comparing = prefix.getBytes(this.charset);
        for (int i = 0; i < comparing.length; i++) {
            if (buffer.get() != comparing[i]) {
                return false;
            }
        }
        return true;
    } catch (UnsupportedEncodingException e) {
        throw new MessageMappingException("Invalid charset", e);
    } finally {
        // reposition the buffer
        buffer.position(pos);
    }
}
Also used : MessageMappingException(org.springframework.integration.mapping.MessageMappingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with MessageMappingException

use of org.springframework.integration.mapping.MessageMappingException in project spring-integration by spring-projects.

the class DatagramPacketMessageMapper method toMessage.

@Override
public Message<byte[]> toMessage(DatagramPacket packet, @Nullable Map<String, Object> headers) throws Exception {
    int offset = packet.getOffset();
    int length = packet.getLength();
    byte[] payload;
    ByteBuffer buffer = ByteBuffer.wrap(packet.getData(), offset, length);
    Message<byte[]> message = null;
    if (this.lengthCheck) {
        int declaredLength = buffer.getInt();
        if (declaredLength != (length - 4)) {
            throw new MessageMappingException("Incorrect length; expected " + (declaredLength + 4) + ", received " + length);
        }
        offset += 4;
        length -= 4;
    }
    String hostAddress = packet.getAddress().getHostAddress();
    String hostName;
    if (this.lookupHost) {
        hostName = packet.getAddress().getHostName();
    } else {
        hostName = hostAddress;
    }
    int port = packet.getPort();
    // side expects it.
    if (this.acknowledge || startsWith(buffer, IpHeaders.ACK_ADDRESS)) {
        try {
            String headersString = new String(packet.getData(), offset, length, this.charset);
            Matcher matcher = udpHeadersPattern.matcher(headersString);
            if (matcher.find()) {
                // Strip off the ack headers and put in Message headers
                length = length - matcher.end();
                payload = new byte[length];
                System.arraycopy(packet.getData(), offset + matcher.end(), payload, 0, length);
                message = getMessageBuilderFactory().withPayload(payload).setHeader(IpHeaders.ACK_ID, UUID.fromString(matcher.group(2))).setHeader(IpHeaders.ACK_ADDRESS, matcher.group(1)).setHeader(IpHeaders.HOSTNAME, hostName).setHeader(IpHeaders.IP_ADDRESS, hostAddress).setHeader(IpHeaders.PORT, port).setHeader(IpHeaders.PACKET_ADDRESS, packet.getSocketAddress()).copyHeadersIfAbsent(headers).build();
            }
        // on no match, just treat as simple payload
        } catch (UnsupportedEncodingException e) {
            throw new MessageMappingException("Invalid charset", e);
        }
    }
    if (message == null) {
        payload = new byte[length];
        System.arraycopy(packet.getData(), offset, payload, 0, length);
        if (payload.length > 0) {
            message = getMessageBuilderFactory().withPayload(payload).setHeader(IpHeaders.HOSTNAME, hostName).setHeader(IpHeaders.IP_ADDRESS, hostAddress).setHeader(IpHeaders.PORT, port).setHeader(IpHeaders.PACKET_ADDRESS, packet.getSocketAddress()).build();
        }
    }
    return message;
}
Also used : MessageMappingException(org.springframework.integration.mapping.MessageMappingException) Matcher(java.util.regex.Matcher) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteBuffer(java.nio.ByteBuffer)

Aggregations

MessageMappingException (org.springframework.integration.mapping.MessageMappingException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ByteBuffer (java.nio.ByteBuffer)2 DatagramPacket (java.net.DatagramPacket)1 InetSocketAddress (java.net.InetSocketAddress)1 Map (java.util.Map)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1 Matcher (java.util.regex.Matcher)1 MessagingException (javax.mail.MessagingException)1 MimeMessage (javax.mail.internet.MimeMessage)1 Test (org.junit.Test)1 Subscriber (org.reactivestreams.Subscriber)1 AttributeAccessor (org.springframework.core.AttributeAccessor)1 ByteArrayResource (org.springframework.core.io.ByteArrayResource)1 MessageTimeoutException (org.springframework.integration.MessageTimeoutException)1 ReactiveStreamsSubscribableChannel (org.springframework.integration.channel.ReactiveStreamsSubscribableChannel)1 MessagingTemplate (org.springframework.integration.core.MessagingTemplate)1 AbstractEndpoint (org.springframework.integration.endpoint.AbstractEndpoint)1 EventDrivenConsumer (org.springframework.integration.endpoint.EventDrivenConsumer)1