Search in sources :

Example 86 with BeanFactory

use of org.springframework.beans.factory.BeanFactory in project spring-integration by spring-projects.

the class HttpRequestHandlingEndpointSupport method onInit.

/**
 * Locates the {@link MultipartResolver} bean based on the default name defined by the
 * {@link DispatcherServlet#MULTIPART_RESOLVER_BEAN_NAME} constant if available.
 * Sets up default converters if no converters set, or {@link #setMergeWithDefaultConverters(boolean)}
 * was called with true after the converters were set.
 */
@Override
protected void onInit() throws Exception {
    super.onInit();
    BeanFactory beanFactory = getBeanFactory();
    if (this.multipartResolver == null && beanFactory != null) {
        try {
            MultipartResolver multipartResolver = beanFactory.getBean(DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
            if (logger.isDebugEnabled()) {
                logger.debug("Using MultipartResolver [" + multipartResolver + "]");
            }
            this.multipartResolver = multipartResolver;
        } catch (NoSuchBeanDefinitionException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate MultipartResolver with name '" + DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME + "': no multipart request handling will be supported.");
            }
        }
    }
    if (this.messageConverters.size() == 0 || (this.mergeWithDefaultConverters && !this.convertersMerged)) {
        this.messageConverters.addAll(this.defaultMessageConverters);
    }
}
Also used : BeanFactory(org.springframework.beans.factory.BeanFactory) MultipartResolver(org.springframework.web.multipart.MultipartResolver) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Example 87 with BeanFactory

use of org.springframework.beans.factory.BeanFactory in project spring-integration by spring-projects.

the class ConnectionFactoryTests method testObtainConnectionIds.

public void testObtainConnectionIds(AbstractServerConnectionFactory serverFactory) throws Exception {
    final List<IpIntegrationEvent> events = Collections.synchronizedList(new ArrayList<IpIntegrationEvent>());
    int expectedEvents = serverFactory instanceof TcpNetServerConnectionFactory ? // Listening, + OPEN, CLOSE, EXCEPTION for each side
    7 : // Listening, + OPEN, CLOSE (but we *might* get exceptions, depending on timing).
    5;
    final CountDownLatch serverListeningLatch = new CountDownLatch(1);
    final CountDownLatch eventLatch = new CountDownLatch(expectedEvents);
    ApplicationEventPublisher publisher = new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
            LogFactory.getLog(this.getClass()).trace("Received: " + event);
            events.add((IpIntegrationEvent) event);
            if (event instanceof TcpConnectionServerListeningEvent) {
                serverListeningLatch.countDown();
            }
            eventLatch.countDown();
        }

        @Override
        public void publishEvent(Object event) {
        }
    };
    serverFactory.setBeanName("serverFactory");
    serverFactory.setApplicationEventPublisher(publisher);
    serverFactory = spy(serverFactory);
    final CountDownLatch serverConnectionInitLatch = new CountDownLatch(1);
    doAnswer(invocation -> {
        Object result = invocation.callRealMethod();
        serverConnectionInitLatch.countDown();
        return result;
    }).when(serverFactory).wrapConnection(any(TcpConnectionSupport.class));
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(10);
    scheduler.afterPropertiesSet();
    BeanFactory bf = mock(BeanFactory.class);
    when(bf.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    when(bf.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)).thenReturn(scheduler);
    serverFactory.setBeanFactory(bf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setOutputChannel(new NullChannel());
    adapter.setConnectionFactory(serverFactory);
    adapter.start();
    assertTrue("Listening event not received", serverListeningLatch.await(10, TimeUnit.SECONDS));
    assertThat(events.get(0), instanceOf(TcpConnectionServerListeningEvent.class));
    assertThat(((TcpConnectionServerListeningEvent) events.get(0)).getPort(), equalTo(serverFactory.getPort()));
    int port = serverFactory.getPort();
    TcpNetClientConnectionFactory clientFactory = new TcpNetClientConnectionFactory("localhost", port);
    clientFactory.registerListener(message -> false);
    clientFactory.setBeanName("clientFactory");
    clientFactory.setApplicationEventPublisher(publisher);
    clientFactory.start();
    TcpConnectionSupport client = clientFactory.getConnection();
    List<String> clients = clientFactory.getOpenConnectionIds();
    assertEquals(1, clients.size());
    assertTrue(clients.contains(client.getConnectionId()));
    assertTrue("Server connection failed to register", serverConnectionInitLatch.await(10, TimeUnit.SECONDS));
    List<String> servers = serverFactory.getOpenConnectionIds();
    assertEquals(1, servers.size());
    assertTrue(serverFactory.closeConnection(servers.get(0)));
    servers = serverFactory.getOpenConnectionIds();
    assertEquals(0, servers.size());
    int n = 0;
    clients = clientFactory.getOpenConnectionIds();
    while (n++ < 100 && clients.size() > 0) {
        Thread.sleep(100);
        clients = clientFactory.getOpenConnectionIds();
    }
    assertEquals(0, clients.size());
    assertTrue(eventLatch.await(10, TimeUnit.SECONDS));
    assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events, events.size(), greaterThanOrEqualTo(expectedEvents));
    FooEvent event = new FooEvent(client, "foo");
    client.publishEvent(event);
    assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events, events.size(), greaterThanOrEqualTo(expectedEvents + 1));
    try {
        event = new FooEvent(mock(TcpConnectionSupport.class), "foo");
        client.publishEvent(event);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertTrue("Can only publish events with this as the source".equals(e.getMessage()));
    }
    SocketAddress address = serverFactory.getServerSocketAddress();
    if (address instanceof InetSocketAddress) {
        InetSocketAddress inetAddress = (InetSocketAddress) address;
        assertEquals(port, inetAddress.getPort());
    }
    serverFactory.stop();
    scheduler.shutdown();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) IpIntegrationEvent(org.springframework.integration.ip.event.IpIntegrationEvent) ApplicationEvent(org.springframework.context.ApplicationEvent) TcpReceivingChannelAdapter(org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) BeanFactory(org.springframework.beans.factory.BeanFactory) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) NullChannel(org.springframework.integration.channel.NullChannel)

Example 88 with BeanFactory

use of org.springframework.beans.factory.BeanFactory in project spring-integration by spring-projects.

the class TcpConnectionEventListenerTests method testNoFilter.

@Test
public void testNoFilter() {
    ApplicationEventListeningMessageProducer eventProducer = new ApplicationEventListeningMessageProducer();
    QueueChannel outputChannel = new QueueChannel();
    eventProducer.setOutputChannel(outputChannel);
    eventProducer.setEventTypes(TcpConnectionEvent.class);
    BeanFactory mock = mock(BeanFactory.class);
    given(mock.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class)).willReturn(mock(ApplicationEventMulticaster.class));
    eventProducer.setBeanFactory(mock);
    eventProducer.afterPropertiesSet();
    eventProducer.start();
    TcpConnectionSupport connection = Mockito.mock(TcpConnectionSupport.class);
    assertTrue(eventProducer.supportsEventType(ResolvableType.forClass(TcpConnectionOpenEvent.class)));
    TcpConnectionEvent event1 = new TcpConnectionOpenEvent(connection, "foo");
    eventProducer.onApplicationEvent(event1);
    assertTrue(eventProducer.supportsEventType(ResolvableType.forClass(FooEvent.class)));
    FooEvent event2 = new FooEvent(connection, "foo");
    eventProducer.onApplicationEvent(event2);
    assertTrue(eventProducer.supportsEventType(ResolvableType.forClass(BarEvent.class)));
    BarEvent event3 = new BarEvent(connection, "foo");
    eventProducer.onApplicationEvent(event3);
    Message<?> message = outputChannel.receive(0);
    assertNotNull(message);
    assertSame(event1, message.getPayload());
    message = outputChannel.receive(0);
    assertNotNull(message);
    assertSame(event2, message.getPayload());
    message = outputChannel.receive(0);
    assertNotNull(message);
    assertSame(event3, message.getPayload());
    message = outputChannel.receive(0);
    assertNull(message);
}
Also used : ApplicationEventMulticaster(org.springframework.context.event.ApplicationEventMulticaster) QueueChannel(org.springframework.integration.channel.QueueChannel) BeanFactory(org.springframework.beans.factory.BeanFactory) ApplicationEventListeningMessageProducer(org.springframework.integration.event.inbound.ApplicationEventListeningMessageProducer) Test(org.junit.Test)

Example 89 with BeanFactory

use of org.springframework.beans.factory.BeanFactory in project spring-integration by spring-projects.

the class OutboundGatewayFunctionTests method testLazyContainerWithDest.

@Test
public void testLazyContainerWithDest() throws Exception {
    BeanFactory beanFactory = mock(BeanFactory.class);
    when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)).thenReturn(scheduler);
    final JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setBeanFactory(beanFactory);
    gateway.setConnectionFactory(getConnectionFactory());
    gateway.setRequestDestination(requestQueue7);
    gateway.setReplyDestination(replyQueue7);
    gateway.setCorrelationKey("JMSCorrelationID");
    gateway.setUseReplyContainer(true);
    gateway.setIdleReplyContainerTimeout(1, TimeUnit.SECONDS);
    gateway.setRequiresReply(true);
    gateway.setReceiveTimeout(20000);
    gateway.afterPropertiesSet();
    gateway.start();
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(() -> {
        JmsTemplate template = new JmsTemplate();
        template.setConnectionFactory(getConnectionFactory());
        template.setReceiveTimeout(20000);
        receiveAndSend(template);
        receiveAndSend(template);
    });
    assertNotNull(gateway.handleRequestMessage(new GenericMessage<>("foo")));
    DefaultMessageListenerContainer container = TestUtils.getPropertyValue(gateway, "replyContainer", DefaultMessageListenerContainer.class);
    int n = 0;
    while (n++ < 100 && container.isRunning()) {
        Thread.sleep(100);
    }
    assertFalse(container.isRunning());
    assertNotNull(gateway.handleRequestMessage(new GenericMessage<>("foo")));
    assertTrue(container.isRunning());
    gateway.stop();
    assertFalse(container.isRunning());
    scheduler.destroy();
    exec.shutdownNow();
}
Also used : DefaultMessageListenerContainer(org.springframework.jms.listener.DefaultMessageListenerContainer) GenericMessage(org.springframework.messaging.support.GenericMessage) BeanFactory(org.springframework.beans.factory.BeanFactory) ExecutorService(java.util.concurrent.ExecutorService) JmsTemplate(org.springframework.jms.core.JmsTemplate) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Test(org.junit.Test)

Example 90 with BeanFactory

use of org.springframework.beans.factory.BeanFactory in project spring-integration by spring-projects.

the class OutboundGatewayFunctionTests method testContainerWithDestName.

@Test
public void testContainerWithDestName() throws Exception {
    BeanFactory beanFactory = mock(BeanFactory.class);
    when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)).thenReturn(scheduler);
    final JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setBeanFactory(beanFactory);
    gateway.setConnectionFactory(getConnectionFactory());
    gateway.setRequestDestination(requestQueue3);
    gateway.setReplyDestinationName("reply3");
    gateway.setCorrelationKey("JMSCorrelationID");
    gateway.setUseReplyContainer(true);
    gateway.afterPropertiesSet();
    gateway.start();
    final AtomicReference<Object> reply = new AtomicReference<Object>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(() -> {
        latch1.countDown();
        try {
            reply.set(gateway.handleRequestMessage(new GenericMessage<String>("foo")));
        } finally {
            latch2.countDown();
        }
    });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    JmsTemplate template = new JmsTemplate();
    template.setConnectionFactory(getConnectionFactory());
    template.setReceiveTimeout(10000);
    javax.jms.Message request = template.receive(requestQueue3);
    assertNotNull(request);
    final javax.jms.Message jmsReply = request;
    template.send(request.getJMSReplyTo(), session -> jmsReply);
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNotNull(reply.get());
    gateway.stop();
    scheduler.destroy();
    exec.shutdownNow();
}
Also used : GenericMessage(org.springframework.messaging.support.GenericMessage) BeanFactory(org.springframework.beans.factory.BeanFactory) ExecutorService(java.util.concurrent.ExecutorService) JmsTemplate(org.springframework.jms.core.JmsTemplate) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Test(org.junit.Test)

Aggregations

BeanFactory (org.springframework.beans.factory.BeanFactory)121 Test (org.junit.jupiter.api.Test)30 ConfigurableBeanFactory (org.springframework.beans.factory.config.ConfigurableBeanFactory)25 Test (org.junit.Test)20 ConfigurableListableBeanFactory (org.springframework.beans.factory.config.ConfigurableListableBeanFactory)16 ListableBeanFactory (org.springframework.beans.factory.ListableBeanFactory)15 ITestBean (org.springframework.beans.testfixture.beans.ITestBean)12 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)11 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)11 CountDownLatch (java.util.concurrent.CountDownLatch)9 ExecutorService (java.util.concurrent.ExecutorService)8 PlatformTransactionManager (org.springframework.transaction.PlatformTransactionManager)8 AutowireCapableBeanFactory (org.springframework.beans.factory.config.AutowireCapableBeanFactory)7 GenericMessage (org.springframework.messaging.support.GenericMessage)7 ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)6 JmsTemplate (org.springframework.jms.core.JmsTemplate)6 Bucket4JAutoConfigurationServletFilter (com.giffing.bucket4j.spring.boot.starter.config.servlet.Bucket4JAutoConfigurationServletFilter)4 Bucket4JAutoConfigurationZuul (com.giffing.bucket4j.spring.boot.starter.config.zuul.Bucket4JAutoConfigurationZuul)4