Search in sources :

Example 26 with ApplicationEvent

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

the class ApplicationEventPublishingMessageHandlerTests method payloadAsEvent.

@Test
public void payloadAsEvent() {
    TestApplicationEventPublisher publisher = new TestApplicationEventPublisher();
    ApplicationEventPublishingMessageHandler handler = new ApplicationEventPublishingMessageHandler();
    handler.setApplicationEventPublisher(publisher);
    assertNull(publisher.getLastEvent());
    Message<?> message = new GenericMessage<TestEvent>(new TestEvent("foo"));
    handler.handleMessage(message);
    ApplicationEvent event = publisher.getLastEvent();
    assertEquals(TestEvent.class, event.getClass());
    assertEquals("foo", ((TestEvent) event).getSource());
}
Also used : GenericMessage(org.springframework.messaging.support.GenericMessage) ApplicationEvent(org.springframework.context.ApplicationEvent) Test(org.junit.Test)

Example 27 with ApplicationEvent

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

the class AnnotatedTests method testHistoryWithAnnotatedComponents.

@Test
public void testHistoryWithAnnotatedComponents() throws Exception {
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("annotated-config.xml", this.getClass());
    ApplicationListener<ApplicationEvent> listener = new ApplicationListener<ApplicationEvent>() {

        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            MessageHistory history = MessageHistory.read((Message<?>) event.getSource());
            Properties adapterHistory = history.get(1);
            assertEquals("myAdapter", adapterHistory.get("name"));
            assertEquals("outbound-channel-adapter", adapterHistory.get("type"));
        }
    };
    listener = spy(listener);
    ac.addApplicationListener(listener);
    MessageChannel channel = ac.getBean("inputChannel", MessageChannel.class);
    EventDrivenConsumer consumer = ac.getBean("myAdapter", EventDrivenConsumer.class);
    MessageHandler handler = (MessageHandler) TestUtils.getPropertyValue(consumer, "handler");
    Field handlerField = consumer.getClass().getDeclaredField("handler");
    handlerField.setAccessible(true);
    handlerField.set(consumer, handler);
    channel.send(new GenericMessage<String>("hello"));
    verify(listener, times(1)).onApplicationEvent((ApplicationEvent) Mockito.any());
    ac.close();
}
Also used : Field(java.lang.reflect.Field) EventDrivenConsumer(org.springframework.integration.endpoint.EventDrivenConsumer) MessageChannel(org.springframework.messaging.MessageChannel) MessageHandler(org.springframework.messaging.MessageHandler) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ApplicationEvent(org.springframework.context.ApplicationEvent) ApplicationListener(org.springframework.context.ApplicationListener) Properties(java.util.Properties) Test(org.junit.Test)

Example 28 with ApplicationEvent

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

the class TcpNioConnectionTests method int3453RaceTest.

@Test
public void int3453RaceTest() throws Exception {
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    final CountDownLatch connectionLatch = new CountDownLatch(1);
    factory.setApplicationEventPublisher(new ApplicationEventPublisher() {

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

        @Override
        public void publishEvent(Object event) {
        }
    });
    final CountDownLatch assemblerLatch = new CountDownLatch(1);
    final AtomicReference<Thread> assembler = new AtomicReference<Thread>();
    factory.registerListener(new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                assembler.set(Thread.currentThread());
                assemblerLatch.countDown();
            }
            return false;
        }
    });
    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    // selector, reader, assembler
    te.setCorePoolSize(3);
    te.setMaxPoolSize(3);
    te.setQueueCapacity(0);
    te.initialize();
    factory.setTaskExecutor(te);
    factory.start();
    TestingUtilities.waitListening(factory, 10000L);
    int port = factory.getPort();
    Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
    assertTrue(connectionLatch.await(10, TimeUnit.SECONDS));
    TcpNioConnection connection = (TcpNioConnection) TestUtils.getPropertyValue(factory, "connections", Map.class).values().iterator().next();
    Log logger = spy(TestUtils.getPropertyValue(connection, "logger", Log.class));
    DirectFieldAccessor dfa = new DirectFieldAccessor(connection);
    dfa.setPropertyValue("logger", logger);
    ChannelInputStream cis = spy(TestUtils.getPropertyValue(connection, "channelInputStream", ChannelInputStream.class));
    dfa.setPropertyValue("channelInputStream", cis);
    // 3 dataAvailable, 1 continuing
    final CountDownLatch readerLatch = new CountDownLatch(4);
    final CountDownLatch readerFinishedLatch = new CountDownLatch(1);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            // delay the reader thread resetting writingToPipe
            readerLatch.await(10, TimeUnit.SECONDS);
            Thread.sleep(100);
            readerFinishedLatch.countDown();
            return null;
        }
    }).when(cis).write(any(ByteBuffer.class));
    doReturn(true).when(logger).isTraceEnabled();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("checking data avail"));
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("Nio assembler continuing"));
    socket.getOutputStream().write("foo\r\n".getBytes());
    assertTrue(assemblerLatch.await(10, TimeUnit.SECONDS));
    assertTrue(readerFinishedLatch.await(10, TimeUnit.SECONDS));
    StackTraceElement[] stackTrace = assembler.get().getStackTrace();
    assertThat(Arrays.asList(stackTrace).toString(), not(containsString("ChannelInputStream.getNextBuffer")));
    socket.close();
    factory.stop();
    te.shutdown();
}
Also used : ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ChannelInputStream(org.springframework.integration.ip.tcp.connection.TcpNioConnection.ChannelInputStream) Log(org.apache.commons.logging.Log) ApplicationEvent(org.springframework.context.ApplicationEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) ErrorMessage(org.springframework.messaging.support.ErrorMessage) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

Example 29 with ApplicationEvent

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

the class ConnectionEventTests method testFailConnect.

@Test
public void testFailConnect() {
    AbstractClientConnectionFactory ccf = new AbstractClientConnectionFactory("junkjunk", 1234) {

        @Override
        protected boolean isActive() {
            return true;
        }

        @Override
        protected TcpConnectionSupport buildNewConnection() throws Exception {
            throw new UnknownHostException("Mocking for test ");
        }
    };
    final AtomicReference<ApplicationEvent> failEvent = new AtomicReference<ApplicationEvent>();
    ccf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            failEvent.set(event);
        }
    });
    ccf.start();
    try {
        ccf.getConnection();
        fail("expected exception");
    } catch (Exception e) {
        assertThat(e, instanceOf(UnknownHostException.class));
        TcpConnectionFailedEvent event = (TcpConnectionFailedEvent) failEvent.get();
        assertSame(e, event.getCause());
    }
    ccf.stop();
}
Also used : UnknownHostException(java.net.UnknownHostException) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEvent(org.springframework.context.ApplicationEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessagingException(org.springframework.messaging.MessagingException) BindException(java.net.BindException) UnknownHostException(java.net.UnknownHostException) Test(org.junit.Test)

Example 30 with ApplicationEvent

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

the class ConnectionEventTests method testConnectionEvents.

@Test
public void testConnectionEvents() throws Exception {
    Socket socket = mock(Socket.class);
    final List<TcpConnectionEvent> theEvent = new ArrayList<TcpConnectionEvent>();
    TcpNetConnection conn = new TcpNetConnection(socket, false, false, new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.add((TcpConnectionEvent) event);
        }

        @Override
        public void publishEvent(Object event) {
        }
    }, "foo");
    /*
		 *  Open is not published by the connection itself; the factory publishes it after initialization.
		 *  See ConnectionToConnectionTests.
		 */
    @SuppressWarnings("unchecked") Serializer<Object> serializer = mock(Serializer.class);
    RuntimeException toBeThrown = new RuntimeException("foo");
    doThrow(toBeThrown).when(serializer).serialize(Mockito.any(Object.class), Mockito.any(OutputStream.class));
    conn.setMapper(new TcpMessageMapper());
    conn.setSerializer(serializer);
    try {
        conn.send(new GenericMessage<String>("bar"));
        fail("Expected exception");
    } catch (Exception e) {
    }
    assertTrue(theEvent.size() > 0);
    assertNotNull(theEvent.get(0));
    assertTrue(theEvent.get(0) instanceof TcpConnectionExceptionEvent);
    assertTrue(theEvent.get(0).toString().endsWith("[factory=foo, connectionId=" + conn.getConnectionId() + "]"));
    assertThat(theEvent.get(0).toString(), containsString("RuntimeException: foo, failedMessage=GenericMessage [payload=bar"));
    TcpConnectionExceptionEvent event = (TcpConnectionExceptionEvent) theEvent.get(0);
    assertNotNull(event.getCause());
    assertSame(toBeThrown, event.getCause().getCause());
    assertTrue(theEvent.size() > 1);
    assertNotNull(theEvent.get(1));
    assertTrue(theEvent.get(1).toString().endsWith("[factory=foo, connectionId=" + conn.getConnectionId() + "] **CLOSED**"));
}
Also used : OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ApplicationEvent(org.springframework.context.ApplicationEvent) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessagingException(org.springframework.messaging.MessagingException) BindException(java.net.BindException) UnknownHostException(java.net.UnknownHostException) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

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