Search in sources :

Example 1 with AbstractIntegrationMessageBuilder

use of org.springframework.integration.support.AbstractIntegrationMessageBuilder in project spring-integration by spring-projects.

the class AbstractMessageSplitter method handleRequestMessage.

@Override
@SuppressWarnings("unchecked")
protected final Object handleRequestMessage(Message<?> message) {
    Object result = this.splitMessage(message);
    // return null if 'null'
    if (result == null) {
        return null;
    }
    boolean reactive = getOutputChannel() instanceof ReactiveStreamsSubscribableChannel;
    setAsync(reactive);
    Iterator<Object> iterator = null;
    Flux<Object> flux = null;
    final int sequenceSize;
    if (result instanceof Iterable<?>) {
        Iterable<Object> iterable = (Iterable<Object>) result;
        sequenceSize = obtainSizeIfPossible(iterable);
        if (reactive) {
            flux = Flux.fromIterable(iterable);
        } else {
            iterator = iterable.iterator();
        }
    } else if (result.getClass().isArray()) {
        Object[] items = (Object[]) result;
        sequenceSize = items.length;
        if (reactive) {
            flux = Flux.fromArray(items);
        } else {
            iterator = Arrays.asList(items).iterator();
        }
    } else if (result instanceof Iterator<?>) {
        Iterator<Object> iter = (Iterator<Object>) result;
        sequenceSize = obtainSizeIfPossible(iter);
        if (reactive) {
            flux = Flux.fromIterable(() -> iter);
        } else {
            iterator = iter;
        }
    } else if (result instanceof Stream<?>) {
        Stream<Object> stream = ((Stream<Object>) result);
        sequenceSize = 0;
        if (reactive) {
            flux = Flux.fromStream(stream);
        } else {
            iterator = stream.iterator();
        }
    } else if (result instanceof Publisher<?>) {
        Publisher<Object> publisher = (Publisher<Object>) result;
        sequenceSize = 0;
        if (reactive) {
            flux = Flux.from(publisher);
        } else {
            iterator = Flux.from((Publisher<Object>) result).toIterable().iterator();
        }
    } else {
        sequenceSize = 1;
        if (reactive) {
            flux = Flux.just(result);
        } else {
            iterator = Collections.singleton(result).iterator();
        }
    }
    if (iterator != null && !iterator.hasNext()) {
        return null;
    }
    Map<String, Object> messageHeaders = message.getHeaders();
    if (willAddHeaders(message)) {
        messageHeaders = new HashMap<>(messageHeaders);
        addHeaders(message, messageHeaders);
    }
    final Map<String, Object> headers = messageHeaders;
    final Object correlationId = message.getHeaders().getId();
    final AtomicInteger sequenceNumber = new AtomicInteger(1);
    Function<Object, AbstractIntegrationMessageBuilder<?>> messageBuilderFunction = object -> createBuilder(object, headers, correlationId, sequenceNumber.getAndIncrement(), sequenceSize);
    if (reactive) {
        return flux.map(messageBuilderFunction);
    } else {
        return new FunctionIterator<>(iterator, messageBuilderFunction);
    }
}
Also used : Arrays(java.util.Arrays) Iterator(java.util.Iterator) Collection(java.util.Collection) Publisher(org.reactivestreams.Publisher) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) HashMap(java.util.HashMap) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) Function(java.util.function.Function) Flux(reactor.core.publisher.Flux) Stream(java.util.stream.Stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Closeable(java.io.Closeable) Map(java.util.Map) Message(org.springframework.messaging.Message) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) Collections(java.util.Collections) FunctionIterator(org.springframework.integration.util.FunctionIterator) FunctionIterator(org.springframework.integration.util.FunctionIterator) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) Publisher(org.reactivestreams.Publisher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) Iterator(java.util.Iterator) FunctionIterator(org.springframework.integration.util.FunctionIterator) Stream(java.util.stream.Stream)

Example 2 with AbstractIntegrationMessageBuilder

use of org.springframework.integration.support.AbstractIntegrationMessageBuilder in project spring-integration by spring-projects.

the class JmsOutboundGateway method createFuture.

private SettableListenableFuture<AbstractIntegrationMessageBuilder<?>> createFuture(final String correlationId) {
    SettableListenableFuture<AbstractIntegrationMessageBuilder<?>> future = new SettableListenableFuture<AbstractIntegrationMessageBuilder<?>>();
    this.futures.put(correlationId, future);
    if (this.receiveTimeout > 0) {
        getTaskScheduler().schedule((Runnable) () -> expire(correlationId), new Date(System.currentTimeMillis() + this.receiveTimeout));
    }
    return future;
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) Date(java.util.Date)

Example 3 with AbstractIntegrationMessageBuilder

use of org.springframework.integration.support.AbstractIntegrationMessageBuilder in project spring-integration by spring-projects.

the class AbstractMessageSource method buildMessage.

@SuppressWarnings("unchecked")
protected Message<T> buildMessage(Object result) {
    Message<T> message = null;
    Map<String, Object> headers = evaluateHeaders();
    if (result instanceof AbstractIntegrationMessageBuilder) {
        if (!CollectionUtils.isEmpty(headers)) {
            ((AbstractIntegrationMessageBuilder<T>) result).copyHeaders(headers);
        }
        message = ((AbstractIntegrationMessageBuilder<T>) result).build();
    } else if (result instanceof Message<?>) {
        try {
            message = (Message<T>) result;
        } catch (Exception e) {
            throw new MessagingException("MessageSource returned unexpected type.", e);
        }
        if (!CollectionUtils.isEmpty(headers)) {
            // create a new Message from this one in order to apply headers
            message = getMessageBuilderFactory().fromMessage(message).copyHeaders(headers).build();
        }
    } else if (result != null) {
        T payload;
        try {
            payload = (T) result;
        } catch (Exception e) {
            throw new MessagingException("MessageSource returned unexpected type.", e);
        }
        message = getMessageBuilderFactory().withPayload(payload).copyHeaders(headers).build();
    }
    if (this.countsEnabled && message != null) {
        if (this.metricsCaptor != null) {
            incrementReceiveCounter();
        }
        this.messageCount.incrementAndGet();
    }
    return message;
}
Also used : Message(org.springframework.messaging.Message) MessagingException(org.springframework.messaging.MessagingException) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) MessagingException(org.springframework.messaging.MessagingException)

Example 4 with AbstractIntegrationMessageBuilder

use of org.springframework.integration.support.AbstractIntegrationMessageBuilder in project spring-integration by spring-projects.

the class AbstractMessageProducingHandler method produceOutput.

protected void produceOutput(Object reply, final Message<?> requestMessage) {
    final MessageHeaders requestHeaders = requestMessage.getHeaders();
    Object replyChannel = null;
    if (getOutputChannel() == null) {
        Map<?, ?> routingSlipHeader = requestHeaders.get(IntegrationMessageHeaderAccessor.ROUTING_SLIP, Map.class);
        if (routingSlipHeader != null) {
            Assert.isTrue(routingSlipHeader.size() == 1, "The RoutingSlip header value must be a SingletonMap");
            Object key = routingSlipHeader.keySet().iterator().next();
            Object value = routingSlipHeader.values().iterator().next();
            Assert.isInstanceOf(List.class, key, "The RoutingSlip key must be List");
            Assert.isInstanceOf(Integer.class, value, "The RoutingSlip value must be Integer");
            List<?> routingSlip = (List<?>) key;
            AtomicInteger routingSlipIndex = new AtomicInteger((Integer) value);
            replyChannel = getOutputChannelFromRoutingSlip(reply, requestMessage, routingSlip, routingSlipIndex);
            if (replyChannel != null) {
                // TODO Migrate to the SF MessageBuilder
                AbstractIntegrationMessageBuilder<?> builder = null;
                if (reply instanceof Message) {
                    builder = this.getMessageBuilderFactory().fromMessage((Message<?>) reply);
                } else if (reply instanceof AbstractIntegrationMessageBuilder) {
                    builder = (AbstractIntegrationMessageBuilder<?>) reply;
                } else {
                    builder = this.getMessageBuilderFactory().withPayload(reply);
                }
                builder.setHeader(IntegrationMessageHeaderAccessor.ROUTING_SLIP, Collections.singletonMap(routingSlip, routingSlipIndex.get()));
                reply = builder;
            }
        }
        if (replyChannel == null) {
            replyChannel = requestHeaders.getReplyChannel();
            if (replyChannel == null && reply instanceof Message) {
                replyChannel = ((Message<?>) reply).getHeaders().getReplyChannel();
            }
        }
    }
    if (this.async && (reply instanceof ListenableFuture<?> || reply instanceof Publisher<?>)) {
        if (reply instanceof ListenableFuture<?> || !(getOutputChannel() instanceof ReactiveStreamsSubscribableChannel)) {
            ListenableFuture<?> future;
            if (reply instanceof ListenableFuture<?>) {
                future = (ListenableFuture<?>) reply;
            } else {
                SettableListenableFuture<Object> settableListenableFuture = new SettableListenableFuture<>();
                Mono.from((Publisher<?>) reply).subscribe(settableListenableFuture::set, settableListenableFuture::setException);
                future = settableListenableFuture;
            }
            Object theReplyChannel = replyChannel;
            future.addCallback(new ListenableFutureCallback<Object>() {

                @Override
                public void onSuccess(Object result) {
                    Message<?> replyMessage = null;
                    try {
                        replyMessage = createOutputMessage(result, requestHeaders);
                        sendOutput(replyMessage, theReplyChannel, false);
                    } catch (Exception e) {
                        Exception exceptionToLogAndSend = e;
                        if (!(e instanceof MessagingException)) {
                            exceptionToLogAndSend = new MessageHandlingException(requestMessage, e);
                            if (replyMessage != null) {
                                exceptionToLogAndSend = new MessagingException(replyMessage, exceptionToLogAndSend);
                            }
                        }
                        logger.error("Failed to send async reply: " + result.toString(), exceptionToLogAndSend);
                        onFailure(exceptionToLogAndSend);
                    }
                }

                @Override
                public void onFailure(Throwable ex) {
                    sendErrorMessage(requestMessage, ex);
                }
            });
        } else {
            ((ReactiveStreamsSubscribableChannel) getOutputChannel()).subscribeTo(Flux.from((Publisher<?>) reply).map(result -> createOutputMessage(result, requestHeaders)));
        }
    } else {
        sendOutput(createOutputMessage(reply, requestHeaders), replyChannel, false);
    }
}
Also used : MessagingException(org.springframework.messaging.MessagingException) Arrays(java.util.Arrays) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) HashMap(java.util.HashMap) ErrorMessage(org.springframework.messaging.support.ErrorMessage) ListenableFutureCallback(org.springframework.util.concurrent.ListenableFutureCallback) MessagingTemplate(org.springframework.integration.core.MessagingTemplate) HashSet(java.util.HashSet) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Map(java.util.Map) IntegrationMessageHeaderAccessor(org.springframework.integration.IntegrationMessageHeaderAccessor) RoutingSlipRouteStrategy(org.springframework.integration.routingslip.RoutingSlipRouteStrategy) Message(org.springframework.messaging.Message) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) Collection(java.util.Collection) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) PatternMatchUtils(org.springframework.util.PatternMatchUtils) Set(java.util.Set) Mono(reactor.core.publisher.Mono) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) DestinationResolutionException(org.springframework.messaging.core.DestinationResolutionException) MessageProducer(org.springframework.integration.core.MessageProducer) MessageChannel(org.springframework.messaging.MessageChannel) MessageHeaders(org.springframework.messaging.MessageHeaders) Flux(reactor.core.publisher.Flux) List(java.util.List) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) MessagingException(org.springframework.messaging.MessagingException) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) Publisher(org.reactivestreams.Publisher) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) DestinationResolutionException(org.springframework.messaging.core.DestinationResolutionException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) List(java.util.List) MessageHeaders(org.springframework.messaging.MessageHeaders)

Example 5 with AbstractIntegrationMessageBuilder

use of org.springframework.integration.support.AbstractIntegrationMessageBuilder in project spring-integration by spring-projects.

the class JmsOutboundGateway method doSendAndReceiveAsync.

private Object doSendAndReceiveAsync(Destination requestDestination, javax.jms.Message jmsRequest, Session session, int priority) throws JMSException {
    String correlationId = null;
    MessageProducer messageProducer = null;
    try {
        messageProducer = session.createProducer(requestDestination);
        correlationId = this.gatewayCorrelation + "_" + Long.toString(this.correlationId.incrementAndGet());
        if (this.correlationKey.equals("JMSCorrelationID")) {
            jmsRequest.setJMSCorrelationID(correlationId);
        } else {
            jmsRequest.setStringProperty(this.correlationKey, correlationId);
            /*
				 * Remove any existing correlation id that was mapped from the inbound message
				 * (it will be restored in the reply by normal ARPMH header processing).
				 */
            jmsRequest.setJMSCorrelationID(null);
        }
        LinkedBlockingQueue<javax.jms.Message> replyQueue = null;
        if (logger.isDebugEnabled()) {
            logger.debug(this.getComponentName() + " Sending message with correlationId " + correlationId);
        }
        SettableListenableFuture<AbstractIntegrationMessageBuilder<?>> future = null;
        boolean async = isAsync();
        if (!async) {
            replyQueue = new LinkedBlockingQueue<javax.jms.Message>(1);
            this.replies.put(correlationId, replyQueue);
        } else {
            future = createFuture(correlationId);
        }
        this.sendRequestMessage(jmsRequest, messageProducer, priority);
        if (async) {
            return future;
        } else {
            return obtainReplyFromContainer(correlationId, replyQueue);
        }
    } finally {
        JmsUtils.closeMessageProducer(messageProducer);
        if (correlationId != null && !isAsync()) {
            this.replies.remove(correlationId);
        }
    }
}
Also used : Message(org.springframework.messaging.Message) AbstractIntegrationMessageBuilder(org.springframework.integration.support.AbstractIntegrationMessageBuilder) MessageProducer(javax.jms.MessageProducer)

Aggregations

AbstractIntegrationMessageBuilder (org.springframework.integration.support.AbstractIntegrationMessageBuilder)5 Message (org.springframework.messaging.Message)4 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Publisher (org.reactivestreams.Publisher)2 ReactiveStreamsSubscribableChannel (org.springframework.integration.channel.ReactiveStreamsSubscribableChannel)2 MessagingException (org.springframework.messaging.MessagingException)2 SettableListenableFuture (org.springframework.util.concurrent.SettableListenableFuture)2 Flux (reactor.core.publisher.Flux)2 Closeable (java.io.Closeable)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Set (java.util.Set)1 Function (java.util.function.Function)1