Search in sources :

Example 31 with ApplicationEvent

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

the class ConnectionEventTests method testInboundGatewayNoConnectionEvents.

@Test
public void testInboundGatewayNoConnectionEvents() {
    TcpInboundGateway gw = new TcpInboundGateway();
    AbstractServerConnectionFactory scf = new AbstractServerConnectionFactory(0) {

        @Override
        public void run() {
        }
    };
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    scf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }
    });
    gw.setConnectionFactory(scf);
    DirectChannel requestChannel = new DirectChannel();
    requestChannel.subscribe(message -> ((MessageChannel) message.getHeaders().getReplyChannel()).send(message));
    gw.setRequestChannel(requestChannel);
    gw.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar").build();
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    assertSame(message, ((MessagingException) event.getCause()).getFailedMessage());
    gw.stop();
    scf.stop();
}
Also used : DirectChannel(org.springframework.integration.channel.DirectChannel) TcpInboundGateway(org.springframework.integration.ip.tcp.TcpInboundGateway) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEvent(org.springframework.context.ApplicationEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.Test)

Example 32 with ApplicationEvent

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

the class CachingClientConnectionFactoryTests method mockedTcpNioConnection.

private TcpConnectionSupport mockedTcpNioConnection() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    new DirectFieldAccessor(socketChannel).setPropertyValue("open", false);
    doThrow(new IOException("Foo")).when(socketChannel).write(Mockito.any(ByteBuffer.class));
    when(socketChannel.socket()).thenReturn(mock(Socket.class));
    TcpNioConnection conn = new TcpNioConnection(socketChannel, false, false, new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
        }

        @Override
        public void publishEvent(Object event) {
        }
    }, "foo");
    conn.setMapper(new TcpMessageMapper());
    conn.setSerializer(new ByteArrayCrLfSerializer());
    return conn;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ByteArrayCrLfSerializer(org.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEvent(org.springframework.context.ApplicationEvent) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Socket(java.net.Socket)

Example 33 with ApplicationEvent

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

the class CachingClientConnectionFactoryTests method mockedTcpNetConnection.

private TcpConnectionSupport mockedTcpNetConnection() throws IOException {
    Socket socket = mock(Socket.class);
    // closed when next retrieved
    when(socket.isClosed()).thenReturn(true);
    OutputStream stream = mock(OutputStream.class);
    doThrow(new IOException("Foo")).when(stream).write(any(byte[].class), anyInt(), anyInt());
    when(socket.getOutputStream()).thenReturn(stream);
    TcpNetConnection conn = new TcpNetConnection(socket, false, false, new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
        }

        @Override
        public void publishEvent(Object event) {
        }
    }, "foo");
    conn.setMapper(new TcpMessageMapper());
    conn.setSerializer(new ByteArrayCrLfSerializer());
    return conn;
}
Also used : ByteArrayCrLfSerializer(org.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer) OutputStream(java.io.OutputStream) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEvent(org.springframework.context.ApplicationEvent) IOException(java.io.IOException) Socket(java.net.Socket)

Example 34 with ApplicationEvent

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

the class ConnectionTimeoutTests method getCloseLatch.

private CountDownLatch getCloseLatch(AbstractClientConnectionFactory client) {
    final CountDownLatch clientClosedLatch;
    clientClosedLatch = new CountDownLatch(1);
    client.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
            if (event instanceof TcpConnectionCloseEvent) {
                clientClosedLatch.countDown();
            }
        }

        @Override
        public void publishEvent(Object event) {
        }
    });
    return clientClosedLatch;
}
Also used : ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEvent(org.springframework.context.ApplicationEvent) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 35 with ApplicationEvent

use of org.springframework.context.ApplicationEvent 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)

Aggregations

ApplicationEvent (org.springframework.context.ApplicationEvent)44 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)16 Test (org.junit.Test)14 Test (org.junit.jupiter.api.Test)11 ApplicationListener (org.springframework.context.ApplicationListener)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)8 ArrayList (java.util.ArrayList)7 PayloadApplicationEvent (org.springframework.context.PayloadApplicationEvent)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)6 ApplicationContext (org.springframework.context.ApplicationContext)6 StaticApplicationContext (org.springframework.context.support.StaticApplicationContext)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 Matchers.containsString (org.hamcrest.Matchers.containsString)5 Socket (java.net.Socket)4 List (java.util.List)4 AbstractApplicationContext (org.springframework.context.support.AbstractApplicationContext)4 IOException (java.io.IOException)3 InOrder (org.mockito.InOrder)3 ApplicationReadyEvent (org.springframework.boot.context.event.ApplicationReadyEvent)3 ApplicationStartedEvent (org.springframework.boot.context.event.ApplicationStartedEvent)3