Search in sources :

Example 1 with MessageProducer

use of org.springframework.integration.core.MessageProducer in project spring-integration by spring-projects.

the class AbstractSimpleMessageHandlerFactoryBean method createHandlerInternal.

protected final H createHandlerInternal() {
    synchronized (this.initializationMonitor) {
        if (this.initialized) {
            // There was a problem when this method was called already
            return null;
        }
        this.handler = createHandler();
        if (this.handler instanceof ApplicationContextAware && this.applicationContext != null) {
            ((ApplicationContextAware) this.handler).setApplicationContext(this.applicationContext);
        }
        if (this.handler instanceof BeanFactoryAware && getBeanFactory() != null) {
            ((BeanFactoryAware) this.handler).setBeanFactory(getBeanFactory());
        }
        if (this.handler instanceof BeanNameAware && this.beanName != null) {
            ((BeanNameAware) this.handler).setBeanName(this.beanName);
        }
        if (this.handler instanceof ApplicationEventPublisherAware && this.applicationEventPublisher != null) {
            ((ApplicationEventPublisherAware) this.handler).setApplicationEventPublisher(this.applicationEventPublisher);
        }
        if (this.handler instanceof MessageProducer && this.outputChannel != null) {
            ((MessageProducer) this.handler).setOutputChannel(this.outputChannel);
        }
        Object actualHandler = extractTarget(this.handler);
        if (actualHandler == null) {
            actualHandler = this.handler;
        }
        if (actualHandler instanceof IntegrationObjectSupport) {
            if (this.componentName != null) {
                ((IntegrationObjectSupport) actualHandler).setComponentName(this.componentName);
            }
            if (this.channelResolver != null) {
                ((IntegrationObjectSupport) actualHandler).setChannelResolver(this.channelResolver);
            }
        }
        if (!CollectionUtils.isEmpty(this.adviceChain)) {
            if (actualHandler instanceof AbstractReplyProducingMessageHandler) {
                ((AbstractReplyProducingMessageHandler) actualHandler).setAdviceChain(this.adviceChain);
            } else if (this.logger.isDebugEnabled()) {
                String name = this.componentName;
                if (name == null && actualHandler instanceof NamedComponent) {
                    name = ((NamedComponent) actualHandler).getComponentName();
                }
                this.logger.debug("adviceChain can only be set on an AbstractReplyProducingMessageHandler" + (name == null ? "" : (", " + name)) + ".");
            }
        }
        if (this.async != null) {
            if (actualHandler instanceof AbstractMessageProducingHandler) {
                ((AbstractMessageProducingHandler) actualHandler).setAsync(this.async);
            }
        }
        if (this.handler instanceof Orderable && this.order != null) {
            ((Orderable) this.handler).setOrder(this.order);
        }
        this.initialized = true;
    }
    if (this.handler instanceof InitializingBean) {
        try {
            ((InitializingBean) this.handler).afterPropertiesSet();
        } catch (Exception e) {
            throw new BeanInitializationException("failed to initialize MessageHandler", e);
        }
    }
    return this.handler;
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) ApplicationContextAware(org.springframework.context.ApplicationContextAware) IntegrationObjectSupport(org.springframework.integration.context.IntegrationObjectSupport) Orderable(org.springframework.integration.context.Orderable) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) NamedComponent(org.springframework.integration.support.context.NamedComponent) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) BeansException(org.springframework.beans.BeansException) BeanNameAware(org.springframework.beans.factory.BeanNameAware) BeanFactoryAware(org.springframework.beans.factory.BeanFactoryAware) AbstractMessageProducingHandler(org.springframework.integration.handler.AbstractMessageProducingHandler) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) MessageProducer(org.springframework.integration.core.MessageProducer) InitializingBean(org.springframework.beans.factory.InitializingBean)

Example 2 with MessageProducer

use of org.springframework.integration.core.MessageProducer in project spring-integration by spring-projects.

the class ScatterGatherHandler method doInit.

@Override
protected void doInit() {
    if (this.gatherChannel == null) {
        this.gatherChannel = new FixedSubscriberChannel(this.gatherer);
    } else {
        if (this.gatherChannel instanceof SubscribableChannel) {
            this.gatherEndpoint = new EventDrivenConsumer((SubscribableChannel) this.gatherChannel, this.gatherer);
        } else if (this.gatherChannel instanceof PollableChannel) {
            this.gatherEndpoint = new PollingConsumer((PollableChannel) this.gatherChannel, this.gatherer);
            ((PollingConsumer) this.gatherEndpoint).setReceiveTimeout(this.gatherTimeout);
        } else {
            throw new MessagingException("Unsupported 'replyChannel' type [" + this.gatherChannel.getClass() + "]." + "SubscribableChannel or PollableChannel type are supported.");
        }
        this.gatherEndpoint.setBeanFactory(this.getBeanFactory());
        this.gatherEndpoint.afterPropertiesSet();
    }
    ((MessageProducer) this.gatherer).setOutputChannel(new FixedSubscriberChannel(message -> {
        MessageHeaders headers = message.getHeaders();
        if (headers.containsKey(GATHER_RESULT_CHANNEL)) {
            Object gatherResultChannel = headers.get(GATHER_RESULT_CHANNEL);
            if (gatherResultChannel instanceof MessageChannel) {
                messagingTemplate.send((MessageChannel) gatherResultChannel, message);
            } else if (gatherResultChannel instanceof String) {
                messagingTemplate.send((String) gatherResultChannel, message);
            }
        } else {
            throw new MessageDeliveryException(message, "The 'gatherResultChannel' header is required to delivery gather result.");
        }
    }));
    this.replyChannelRegistry = getBeanFactory().getBean(IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME, HeaderChannelRegistry.class);
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) AbstractEndpoint(org.springframework.integration.endpoint.AbstractEndpoint) HeaderChannelRegistry(org.springframework.integration.support.channel.HeaderChannelRegistry) ClassUtils(org.springframework.util.ClassUtils) AopUtils(org.springframework.aop.support.AopUtils) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) SubscribableChannel(org.springframework.messaging.SubscribableChannel) MessageProducer(org.springframework.integration.core.MessageProducer) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) MessageChannel(org.springframework.messaging.MessageChannel) MessageHeaders(org.springframework.messaging.MessageHeaders) IntegrationContextUtils(org.springframework.integration.context.IntegrationContextUtils) Lifecycle(org.springframework.context.Lifecycle) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) EventDrivenConsumer(org.springframework.integration.endpoint.EventDrivenConsumer) MessageHandler(org.springframework.messaging.MessageHandler) FixedSubscriberChannel(org.springframework.integration.channel.FixedSubscriberChannel) Message(org.springframework.messaging.Message) PollableChannel(org.springframework.messaging.PollableChannel) Assert(org.springframework.util.Assert) EventDrivenConsumer(org.springframework.integration.endpoint.EventDrivenConsumer) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) MessagingException(org.springframework.messaging.MessagingException) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) HeaderChannelRegistry(org.springframework.integration.support.channel.HeaderChannelRegistry) MessageChannel(org.springframework.messaging.MessageChannel) PollableChannel(org.springframework.messaging.PollableChannel) MessageProducer(org.springframework.integration.core.MessageProducer) MessageHeaders(org.springframework.messaging.MessageHeaders) SubscribableChannel(org.springframework.messaging.SubscribableChannel) FixedSubscriberChannel(org.springframework.integration.channel.FixedSubscriberChannel)

Example 3 with MessageProducer

use of org.springframework.integration.core.MessageProducer in project spring-cloud-stream by spring-cloud.

the class AbstractMessageChannelBinder method doBindConsumer.

/**
 * Binds an inbound channel to a given destination. The implementation delegates to
 * {@link ProvisioningProvider#provisionConsumerDestination(String, String, ConsumerProperties)}
 * and
 * {@link #createConsumerEndpoint(ConsumerDestination, String, ConsumerProperties)}
 * for handling middleware-specific logic. If the returned consumer endpoint is an
 * {@link InitializingBean} then {@link InitializingBean#afterPropertiesSet()} will be
 * called on it. Similarly, if the returned consumer endpoint is a {@link Lifecycle},
 * then {@link Lifecycle#start()} will be called on it.
 *
 * @param name the name of the destination
 * @param group the consumer group
 * @param inputChannel the channel to be bound
 * @param properties the {@link ConsumerProperties} of the binding
 * @return the Binding for the channel
 * @throws BinderException on internal errors during binding
 */
@Override
public final Binding<MessageChannel> doBindConsumer(String name, String group, MessageChannel inputChannel, final C properties) throws BinderException {
    MessageProducer consumerEndpoint = null;
    try {
        ConsumerDestination destination = this.provisioningProvider.provisionConsumerDestination(name, group, properties);
        if (HeaderMode.embeddedHeaders.equals(properties.getHeaderMode())) {
            enhanceMessageChannel(inputChannel);
        }
        consumerEndpoint = createConsumerEndpoint(destination, group, properties);
        consumerEndpoint.setOutputChannel(inputChannel);
        if (consumerEndpoint instanceof InitializingBean) {
            ((InitializingBean) consumerEndpoint).afterPropertiesSet();
        }
        if (consumerEndpoint instanceof Lifecycle) {
            ((Lifecycle) consumerEndpoint).start();
        }
        Binding<MessageChannel> binding = new DefaultBinding<MessageChannel>(name, group, inputChannel, consumerEndpoint instanceof Lifecycle ? (Lifecycle) consumerEndpoint : null) {

            @Override
            public Map<String, Object> getExtendedInfo() {
                return doGetExtendedInfo(destination, properties);
            }

            @Override
            protected void afterUnbind() {
                try {
                    if (getEndpoint() instanceof DisposableBean) {
                        ((DisposableBean) getEndpoint()).destroy();
                    }
                } catch (Exception e) {
                    AbstractMessageChannelBinder.this.logger.error("Exception thrown while unbinding " + toString(), e);
                }
                afterUnbindConsumer(destination, this.group, properties);
                destroyErrorInfrastructure(destination, group, properties);
            }
        };
        doPublishEvent(new BindingCreatedEvent(binding));
        return binding;
    } catch (Exception e) {
        if (consumerEndpoint instanceof Lifecycle) {
            ((Lifecycle) consumerEndpoint).stop();
        }
        if (e instanceof BinderException) {
            throw (BinderException) e;
        } else if (e instanceof ProvisioningException) {
            throw (ProvisioningException) e;
        } else {
            throw new BinderException("Exception thrown while starting consumer: ", e);
        }
    }
}
Also used : Lifecycle(org.springframework.context.Lifecycle) ConsumerDestination(org.springframework.cloud.stream.provisioning.ConsumerDestination) ProvisioningException(org.springframework.cloud.stream.provisioning.ProvisioningException) AbstractMessageChannel(org.springframework.integration.channel.AbstractMessageChannel) MessageChannel(org.springframework.messaging.MessageChannel) DisposableBean(org.springframework.beans.factory.DisposableBean) ProvisioningException(org.springframework.cloud.stream.provisioning.ProvisioningException) MessageProducer(org.springframework.integration.core.MessageProducer) InitializingBean(org.springframework.beans.factory.InitializingBean)

Example 4 with MessageProducer

use of org.springframework.integration.core.MessageProducer in project spring-cloud-stream by spring-cloud.

the class AbstractMessageChannelBinderTests method testEndpointLifecycle.

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testEndpointLifecycle() throws Exception {
    AbstractMessageChannelBinder<ConsumerProperties, ProducerProperties, ProvisioningProvider<ConsumerProperties, ProducerProperties>> binder = context.getBean(AbstractMessageChannelBinder.class);
    ConsumerProperties consumerProperties = new ConsumerProperties();
    // to force error infrastructure creation
    consumerProperties.setMaxAttempts(1);
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo", "fooGroup", new DirectChannel(), consumerProperties);
    DirectFieldAccessor consumerBindingAccessor = new DirectFieldAccessor(consumerBinding);
    MessageProducer messageProducer = (MessageProducer) consumerBindingAccessor.getPropertyValue("lifecycle");
    assertTrue(((Lifecycle) messageProducer).isRunning());
    assertNotNull(messageProducer.getOutputChannel());
    SubscribableChannel errorChannel = (SubscribableChannel) consumerBindingAccessor.getPropertyValue("lifecycle.errorChannel");
    assertThat(errorChannel).isNotNull();
    Set<MessageHandler> handlers = TestUtils.getPropertyValue(errorChannel, "dispatcher.handlers", Set.class);
    assertThat(handlers.size()).isEqualTo(2);
    Iterator<MessageHandler> iterator = handlers.iterator();
    assertThat(iterator.next()).isInstanceOf(BridgeHandler.class);
    assertThat(iterator.next()).isInstanceOf(LastSubscriberMessageHandler.class);
    assertThat(context.containsBean("foo.fooGroup.errors")).isTrue();
    assertThat(context.containsBean("foo.fooGroup.errors.recoverer")).isTrue();
    assertThat(context.containsBean("foo.fooGroup.errors.handler")).isTrue();
    assertThat(context.containsBean("foo.fooGroup.errors.bridge")).isTrue();
    consumerBinding.unbind();
    assertThat(context.containsBean("foo.fooGroup.errors")).isFalse();
    assertThat(context.containsBean("foo.fooGroup.errors.recoverer")).isFalse();
    assertThat(context.containsBean("foo.fooGroup.errors.handler")).isFalse();
    assertThat(context.containsBean("foo.fooGroup.errors.bridge")).isFalse();
    assertFalse(((Lifecycle) messageProducer).isRunning());
    ProducerProperties producerProps = new ProducerProperties();
    producerProps.setErrorChannelEnabled(true);
    Binding<MessageChannel> producerBinding = binder.bindProducer("bar", new DirectChannel(), producerProps);
    assertThat(context.containsBean("bar.errors")).isTrue();
    assertThat(context.containsBean("bar.errors.bridge")).isTrue();
    producerBinding.unbind();
    assertThat(context.containsBean("bar.errors")).isFalse();
    assertThat(context.containsBean("bar.errors.bridge")).isFalse();
}
Also used : MessageHandler(org.springframework.messaging.MessageHandler) DirectChannel(org.springframework.integration.channel.DirectChannel) MessageChannel(org.springframework.messaging.MessageChannel) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ProvisioningProvider(org.springframework.cloud.stream.provisioning.ProvisioningProvider) MessageProducer(org.springframework.integration.core.MessageProducer) SubscribableChannel(org.springframework.messaging.SubscribableChannel) Test(org.junit.Test)

Example 5 with MessageProducer

use of org.springframework.integration.core.MessageProducer in project spring-integration by spring-projects.

the class MessageHandlerChain method configureChain.

private void configureChain() {
    Assert.isTrue(this.handlers.size() == new HashSet<MessageHandler>(this.handlers).size(), "duplicate handlers are not allowed in a chain");
    for (int i = 0; i < this.handlers.size(); i++) {
        MessageHandler handler = this.handlers.get(i);
        if (i < this.handlers.size() - 1) {
            // not the last handler
            Assert.isInstanceOf(MessageProducer.class, handler, "All handlers except for " + "the last one in the chain must implement the MessageProducer interface.");
            MessageHandler nextHandler = this.handlers.get(i + 1);
            MessageChannel nextChannel = (message, timeout) -> {
                nextHandler.handleMessage(message);
                return true;
            };
            ((MessageProducer) handler).setOutputChannel(nextChannel);
            // to 'force' re-init it for check its configuration in conjunction with current MessageHandlerChain.
            if (handler instanceof MessageHandlerChain) {
                ((MessageHandlerChain) handler).initialized = false;
                ((MessageHandlerChain) handler).afterPropertiesSet();
            }
        } else if (handler instanceof MessageProducer) {
            MessageChannel replyChannel = new ReplyForwardingMessageChannel();
            ((MessageProducer) handler).setOutputChannel(replyChannel);
        } else {
            Assert.isNull(getOutputChannel(), "An output channel was provided, but the final handler in " + "the chain does not implement the MessageProducer interface.");
        }
    }
}
Also used : HashSet(java.util.HashSet) List(java.util.List) ReentrantLock(java.util.concurrent.locks.ReentrantLock) MessageHandler(org.springframework.messaging.MessageHandler) MessageFilter(org.springframework.integration.filter.MessageFilter) Message(org.springframework.messaging.Message) MessageProducer(org.springframework.integration.core.MessageProducer) MessageChannel(org.springframework.messaging.MessageChannel) Collections(java.util.Collections) Lifecycle(org.springframework.context.Lifecycle) Assert(org.springframework.util.Assert) MessageHandler(org.springframework.messaging.MessageHandler) MessageChannel(org.springframework.messaging.MessageChannel) MessageProducer(org.springframework.integration.core.MessageProducer)

Aggregations

MessageProducer (org.springframework.integration.core.MessageProducer)9 MessageChannel (org.springframework.messaging.MessageChannel)6 Lifecycle (org.springframework.context.Lifecycle)5 MessageHandler (org.springframework.messaging.MessageHandler)4 AbstractMessageProducingHandler (org.springframework.integration.handler.AbstractMessageProducingHandler)3 Message (org.springframework.messaging.Message)3 Test (org.junit.Test)2 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)2 DisposableBean (org.springframework.beans.factory.DisposableBean)2 InitializingBean (org.springframework.beans.factory.InitializingBean)2 AbstractReplyProducingMessageHandler (org.springframework.integration.handler.AbstractReplyProducingMessageHandler)2 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Objects (java.util.Objects)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 ReentrantLock (java.util.concurrent.locks.ReentrantLock)1