Search in sources :

Example 6 with NamedComponent

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

the class ChannelSecurityMetadataSource method getAttributes.

public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    Assert.isAssignable(ChannelInvocation.class, object.getClass());
    ChannelInvocation invocation = (ChannelInvocation) object;
    MessageChannel channel = invocation.getChannel();
    Assert.isAssignable(NamedComponent.class, channel.getClass());
    String channelName = ((NamedComponent) channel).getComponentName();
    List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();
    for (Map.Entry<Pattern, ChannelAccessPolicy> mapping : this.patternMappings.entrySet()) {
        Pattern pattern = mapping.getKey();
        ChannelAccessPolicy accessPolicy = mapping.getValue();
        if (pattern.matcher(channelName).matches()) {
            if (invocation.isSend()) {
                Collection<ConfigAttribute> definition = accessPolicy.getConfigAttributesForSend();
                if (definition != null) {
                    attributes.addAll(definition);
                }
            } else if (invocation.isReceive()) {
                Collection<ConfigAttribute> definition = accessPolicy.getConfigAttributesForReceive();
                if (definition != null) {
                    attributes.addAll(definition);
                }
            }
        }
    }
    return attributes;
}
Also used : Pattern(java.util.regex.Pattern) ConfigAttribute(org.springframework.security.access.ConfigAttribute) ArrayList(java.util.ArrayList) NamedComponent(org.springframework.integration.support.context.NamedComponent) MessageChannel(org.springframework.messaging.MessageChannel) Collection(java.util.Collection) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 7 with NamedComponent

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

the class IntegrationFlowBeanPostProcessor method processStandardIntegrationFlow.

private Object processStandardIntegrationFlow(StandardIntegrationFlow flow, String flowBeanName) {
    String flowNamePrefix = flowBeanName + ".";
    int subFlowNameIndex = 0;
    int channelNameIndex = 0;
    Map<Object, String> integrationComponents = flow.getIntegrationComponents();
    Map<Object, String> targetIntegrationComponents = new LinkedHashMap<>(integrationComponents.size());
    for (Map.Entry<Object, String> entry : integrationComponents.entrySet()) {
        Object component = entry.getKey();
        if (component instanceof ConsumerEndpointSpec) {
            ConsumerEndpointSpec<?, ?> endpointSpec = (ConsumerEndpointSpec<?, ?>) component;
            MessageHandler messageHandler = endpointSpec.get().getT2();
            ConsumerEndpointFactoryBean endpoint = endpointSpec.get().getT1();
            String id = endpointSpec.getId();
            if (id == null) {
                id = generateBeanName(endpoint, entry.getValue());
            }
            Collection<?> messageHandlers = this.beanFactory.getBeansOfType(messageHandler.getClass(), false, false).values();
            if (!messageHandlers.contains(messageHandler)) {
                String handlerBeanName = generateBeanName(messageHandler);
                String[] handlerAlias = new String[] { id + IntegrationConfigUtils.HANDLER_ALIAS_SUFFIX };
                registerComponent(messageHandler, handlerBeanName, flowBeanName);
                for (String alias : handlerAlias) {
                    this.beanFactory.registerAlias(handlerBeanName, alias);
                }
            }
            registerComponent(endpoint, id, flowBeanName);
            targetIntegrationComponents.put(endpoint, id);
        } else {
            Collection<?> values = this.beanFactory.getBeansOfType(component.getClass(), false, false).values();
            if (!values.contains(component)) {
                if (component instanceof AbstractMessageChannel) {
                    String channelBeanName = ((AbstractMessageChannel) component).getComponentName();
                    if (channelBeanName == null) {
                        channelBeanName = entry.getValue();
                        if (channelBeanName == null) {
                            channelBeanName = flowNamePrefix + "channel" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + channelNameIndex++;
                        }
                    }
                    registerComponent(component, channelBeanName, flowBeanName);
                    targetIntegrationComponents.put(component, channelBeanName);
                } else if (component instanceof MessageChannelReference) {
                    String channelBeanName = ((MessageChannelReference) component).getName();
                    if (!this.beanFactory.containsBean(channelBeanName)) {
                        DirectChannel directChannel = new DirectChannel();
                        registerComponent(directChannel, channelBeanName, flowBeanName);
                        targetIntegrationComponents.put(directChannel, channelBeanName);
                    }
                } else if (component instanceof FixedSubscriberChannel) {
                    FixedSubscriberChannel fixedSubscriberChannel = (FixedSubscriberChannel) component;
                    String channelBeanName = fixedSubscriberChannel.getComponentName();
                    if ("Unnamed fixed subscriber channel".equals(channelBeanName)) {
                        channelBeanName = flowNamePrefix + "channel" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + channelNameIndex++;
                    }
                    registerComponent(component, channelBeanName, flowBeanName);
                    targetIntegrationComponents.put(component, channelBeanName);
                } else if (component instanceof SourcePollingChannelAdapterSpec) {
                    SourcePollingChannelAdapterSpec spec = (SourcePollingChannelAdapterSpec) component;
                    Map<Object, String> componentsToRegister = spec.getComponentsToRegister();
                    if (!CollectionUtils.isEmpty(componentsToRegister)) {
                        componentsToRegister.entrySet().stream().filter(o -> !this.beanFactory.getBeansOfType(o.getKey().getClass(), false, false).values().contains(o.getKey())).forEach(o -> registerComponent(o.getKey(), generateBeanName(o.getKey(), o.getValue())));
                    }
                    SourcePollingChannelAdapterFactoryBean pollingChannelAdapterFactoryBean = spec.get().getT1();
                    String id = spec.getId();
                    if (!StringUtils.hasText(id)) {
                        id = generateBeanName(pollingChannelAdapterFactoryBean, entry.getValue());
                    }
                    registerComponent(pollingChannelAdapterFactoryBean, id, flowBeanName);
                    targetIntegrationComponents.put(pollingChannelAdapterFactoryBean, id);
                    MessageSource<?> messageSource = spec.get().getT2();
                    if (!this.beanFactory.getBeansOfType(messageSource.getClass(), false, false).values().contains(messageSource)) {
                        String messageSourceId = id + ".source";
                        if (messageSource instanceof NamedComponent && ((NamedComponent) messageSource).getComponentName() != null) {
                            messageSourceId = ((NamedComponent) messageSource).getComponentName();
                        }
                        registerComponent(messageSource, messageSourceId, flowBeanName);
                    }
                } else if (component instanceof StandardIntegrationFlow) {
                    String subFlowBeanName = entry.getValue() != null ? entry.getValue() : flowNamePrefix + "subFlow" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + subFlowNameIndex++;
                    registerComponent(component, subFlowBeanName, flowBeanName);
                    targetIntegrationComponents.put(component, subFlowBeanName);
                } else if (component instanceof AnnotationGatewayProxyFactoryBean) {
                    AnnotationGatewayProxyFactoryBean gateway = (AnnotationGatewayProxyFactoryBean) component;
                    String gatewayId = entry.getValue();
                    if (gatewayId == null) {
                        gatewayId = gateway.getComponentName();
                    }
                    if (gatewayId == null) {
                        gatewayId = flowNamePrefix + "gateway";
                    }
                    registerComponent(gateway, gatewayId, flowBeanName, beanDefinition -> {
                        ((AbstractBeanDefinition) beanDefinition).setSource(new DescriptiveResource(gateway.getObjectType().getName()));
                    });
                    targetIntegrationComponents.put(component, gatewayId);
                } else {
                    String generatedBeanName = generateBeanName(component, entry.getValue());
                    registerComponent(component, generatedBeanName, flowBeanName);
                    targetIntegrationComponents.put(component, generatedBeanName);
                }
            } else {
                targetIntegrationComponents.put(entry.getKey(), entry.getValue());
            }
        }
    }
    flow.setIntegrationComponents(targetIntegrationComponents);
    return flow;
}
Also used : DescriptiveResource(org.springframework.core.io.DescriptiveResource) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) BeanCreationNotAllowedException(org.springframework.beans.factory.BeanCreationNotAllowedException) NamedComponent(org.springframework.integration.support.context.NamedComponent) BeanFactoryUtils(org.springframework.beans.factory.BeanFactoryUtils) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) AbstractMessageChannel(org.springframework.integration.channel.AbstractMessageChannel) MessageSource(org.springframework.integration.core.MessageSource) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) LinkedHashMap(java.util.LinkedHashMap) BeanFactoryAware(org.springframework.beans.factory.BeanFactoryAware) Map(java.util.Map) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) BeanDefinitionCustomizer(org.springframework.beans.factory.config.BeanDefinitionCustomizer) MessageChannelReference(org.springframework.integration.dsl.support.MessageChannelReference) Collection(java.util.Collection) BeansException(org.springframework.beans.BeansException) ConsumerEndpointFactoryBean(org.springframework.integration.config.ConsumerEndpointFactoryBean) SmartInitializingSingleton(org.springframework.beans.factory.SmartInitializingSingleton) BeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor) IntegrationConfigUtils(org.springframework.integration.config.IntegrationConfigUtils) MessageHandler(org.springframework.messaging.MessageHandler) CollectionUtils(org.springframework.util.CollectionUtils) BeanFactory(org.springframework.beans.factory.BeanFactory) FixedSubscriberChannel(org.springframework.integration.channel.FixedSubscriberChannel) SourcePollingChannelAdapterFactoryBean(org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean) AnnotationGatewayProxyFactoryBean(org.springframework.integration.gateway.AnnotationGatewayProxyFactoryBean) DirectChannel(org.springframework.integration.channel.DirectChannel) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MessageHandler(org.springframework.messaging.MessageHandler) DirectChannel(org.springframework.integration.channel.DirectChannel) LinkedHashMap(java.util.LinkedHashMap) MessageChannelReference(org.springframework.integration.dsl.support.MessageChannelReference) ConsumerEndpointFactoryBean(org.springframework.integration.config.ConsumerEndpointFactoryBean) AnnotationGatewayProxyFactoryBean(org.springframework.integration.gateway.AnnotationGatewayProxyFactoryBean) AbstractMessageChannel(org.springframework.integration.channel.AbstractMessageChannel) SourcePollingChannelAdapterFactoryBean(org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean) MessageSource(org.springframework.integration.core.MessageSource) DescriptiveResource(org.springframework.core.io.DescriptiveResource) NamedComponent(org.springframework.integration.support.context.NamedComponent) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) FixedSubscriberChannel(org.springframework.integration.channel.FixedSubscriberChannel)

Example 8 with NamedComponent

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

the class ConsoleInboundChannelAdapterParserTests method adapterWithDefaultCharset.

@Test
public void adapterWithDefaultCharset() {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("consoleInboundChannelAdapterParserTests.xml", ConsoleInboundChannelAdapterParserTests.class);
    SourcePollingChannelAdapter adapter = context.getBean("adapterWithDefaultCharset.adapter", SourcePollingChannelAdapter.class);
    MessageSource<?> source = (MessageSource<?>) new DirectFieldAccessor(adapter).getPropertyValue("source");
    assertTrue(source instanceof NamedComponent);
    assertEquals("adapterWithDefaultCharset.adapter", adapter.getComponentName());
    assertEquals("stream:stdin-channel-adapter(character)", adapter.getComponentType());
    assertEquals("stream:stdin-channel-adapter(character)", ((NamedComponent) source).getComponentType());
    DirectFieldAccessor sourceAccessor = new DirectFieldAccessor(source);
    Reader bufferedReader = (Reader) sourceAccessor.getPropertyValue("reader");
    assertEquals(BufferedReader.class, bufferedReader.getClass());
    DirectFieldAccessor bufferedReaderAccessor = new DirectFieldAccessor(bufferedReader);
    Reader reader = (Reader) bufferedReaderAccessor.getPropertyValue("in");
    assertEquals(InputStreamReader.class, reader.getClass());
    Charset readerCharset = Charset.forName(((InputStreamReader) reader).getEncoding());
    assertEquals(Charset.defaultCharset(), readerCharset);
    Message<?> message = source.receive();
    assertNotNull(message);
    assertEquals("foo", message.getPayload());
    adapter = context.getBean("pipedAdapterNoCharset.adapter", SourcePollingChannelAdapter.class);
    source = adapter.getMessageSource();
    assertTrue(TestUtils.getPropertyValue(source, "blockToDetectEOF", Boolean.class));
    context.close();
}
Also used : ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) MessageSource(org.springframework.integration.core.MessageSource) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Charset(java.nio.charset.Charset) NamedComponent(org.springframework.integration.support.context.NamedComponent) Test(org.junit.Test)

Example 9 with NamedComponent

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

the class IntegrationMBeanExporter method enhanceHandlerMonitor.

private MessageHandlerMetrics enhanceHandlerMonitor(MessageHandlerMetrics monitor) {
    MessageHandlerMetrics result = monitor;
    if (monitor.getManagedName() != null && monitor.getManagedType() != null) {
        return monitor;
    }
    // Assignment algorithm and bean id, with bean id pulled reflectively out of enclosing endpoint if possible
    String[] names = this.applicationContext.getBeanNamesForType(AbstractEndpoint.class);
    String name = null;
    String endpointName = null;
    String source = "endpoint";
    Object endpoint = null;
    for (String beanName : names) {
        endpoint = this.applicationContext.getBean(beanName);
        try {
            Object field = extractTarget(getField(endpoint, "handler"));
            if (field == monitor || this.extractTarget(this.handlerInAnonymousWrapper(field)) == monitor) {
                name = beanName;
                endpointName = beanName;
                break;
            }
        } catch (Exception e) {
            logger.trace("Could not get handler from bean = " + beanName);
        }
    }
    if (name != null && endpoint != null && name.startsWith("_org.springframework.integration")) {
        name = getInternalComponentName(name);
        source = "internal";
    }
    if (name != null && endpoint != null && name.startsWith("org.springframework.integration")) {
        Object target = endpoint;
        if (endpoint instanceof Advised) {
            TargetSource targetSource = ((Advised) endpoint).getTargetSource();
            if (targetSource != null) {
                try {
                    target = targetSource.getTarget();
                } catch (Exception e) {
                    logger.error("Could not get handler from bean = " + name);
                }
            }
        }
        Object field = getField(target, "inputChannel");
        if (field != null) {
            if (!this.anonymousHandlerCounters.containsKey(field)) {
                this.anonymousHandlerCounters.put(field, new AtomicLong());
            }
            AtomicLong count = this.anonymousHandlerCounters.get(field);
            long total = count.incrementAndGet();
            String suffix = "";
            /*
				 * Short hack to makes sure object names are unique if more than one endpoint has the same input channel
				 */
            if (total > 1) {
                suffix = "#" + total;
            }
            name = field + suffix;
            source = "anonymous";
        }
    }
    if (endpoint instanceof Lifecycle) {
        // Wrap the monitor in a lifecycle so it exposes the start/stop operations
        if (monitor instanceof MappingMessageRouterManagement) {
            if (monitor instanceof TrackableComponent) {
                result = new TrackableRouterMetrics((Lifecycle) endpoint, (MappingMessageRouterManagement) monitor);
            } else {
                result = new RouterMetrics((Lifecycle) endpoint, (MappingMessageRouterManagement) monitor);
            }
        } else {
            if (monitor instanceof TrackableComponent) {
                result = new LifecycleTrackableMessageHandlerMetrics((Lifecycle) endpoint, monitor);
            } else {
                result = new LifecycleMessageHandlerMetrics((Lifecycle) endpoint, monitor);
            }
        }
    }
    if (name == null) {
        if (monitor instanceof NamedComponent) {
            name = ((NamedComponent) monitor).getComponentName();
        }
        if (name == null) {
            name = monitor.toString();
        }
        source = "handler";
    }
    if (endpointName != null) {
        this.beansByEndpointName.put(name, endpointName);
    }
    monitor.setManagedType(source);
    monitor.setManagedName(name);
    return result;
}
Also used : TargetSource(org.springframework.aop.TargetSource) TrackableRouterMetrics(org.springframework.integration.support.management.TrackableRouterMetrics) Lifecycle(org.springframework.context.Lifecycle) MappingMessageRouterManagement(org.springframework.integration.support.management.MappingMessageRouterManagement) TrackableComponent(org.springframework.integration.support.management.TrackableComponent) NamedComponent(org.springframework.integration.support.context.NamedComponent) UnableToRegisterMBeanException(org.springframework.jmx.export.UnableToRegisterMBeanException) JMException(javax.management.JMException) BeansException(org.springframework.beans.BeansException) LifecycleTrackableMessageHandlerMetrics(org.springframework.integration.support.management.LifecycleTrackableMessageHandlerMetrics) LifecycleMessageHandlerMetrics(org.springframework.integration.support.management.LifecycleMessageHandlerMetrics) MessageHandlerMetrics(org.springframework.integration.support.management.MessageHandlerMetrics) LifecycleTrackableMessageHandlerMetrics(org.springframework.integration.support.management.LifecycleTrackableMessageHandlerMetrics) AtomicLong(java.util.concurrent.atomic.AtomicLong) LifecycleMessageHandlerMetrics(org.springframework.integration.support.management.LifecycleMessageHandlerMetrics) Advised(org.springframework.aop.framework.Advised) TrackableRouterMetrics(org.springframework.integration.support.management.TrackableRouterMetrics) RouterMetrics(org.springframework.integration.support.management.RouterMetrics)

Aggregations

NamedComponent (org.springframework.integration.support.context.NamedComponent)9 Test (org.junit.Test)3 BeansException (org.springframework.beans.BeansException)3 Collection (java.util.Collection)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 BeanFactoryAware (org.springframework.beans.factory.BeanFactoryAware)2 MessageSource (org.springframework.integration.core.MessageSource)2 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 Charset (java.nio.charset.Charset)1 ArrayList (java.util.ArrayList)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1 Pattern (java.util.regex.Pattern)1 JMException (javax.management.JMException)1 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)1 TargetSource (org.springframework.aop.TargetSource)1 Advised (org.springframework.aop.framework.Advised)1