Example usage for org.springframework.context ApplicationEventPublisher ApplicationEventPublisher

List of usage examples for org.springframework.context ApplicationEventPublisher ApplicationEventPublisher

Introduction

In this page you can find the example usage for org.springframework.context ApplicationEventPublisher ApplicationEventPublisher.

Prototype

ApplicationEventPublisher

Source Link

Usage

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

@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//from   w w  w. jav  a2 s . co  m
        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**"));
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

@Test
public void testOutboundChannelAdapterNoConnectionEvents() {
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    AbstractServerConnectionFactory scf = new AbstractServerConnectionFactory(0) {

        @Override//from w  w w  .ja  v a 2  s  .c om
        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);
        }

    });
    handler.setConnectionFactory(scf);
    handler.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar")
            .build();
    try {
        handler.handleMessage(message);
        fail("expected exception");
    } catch (MessageHandlingException e) {
        assertThat(e.getMessage(), Matchers.containsString("Unable to find outbound socket"));
    }
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    assertSame(message, ((MessagingException) event.getCause()).getFailedMessage());
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

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

        @Override/*from   w  ww  . j ava  2s .  com*/
        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(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            ((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());
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

@Test
public void testOutboundGatewayNoConnectionEvents() {
    TcpOutboundGateway gw = new TcpOutboundGateway();
    AbstractClientConnectionFactory ccf = new AbstractClientConnectionFactory("localhost", 0) {
    };// w  ww  . j a  v  a  2  s .  c om
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    ccf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

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

    });
    gw.setConnectionFactory(ccf);
    DirectChannel requestChannel = new DirectChannel();
    requestChannel
            .subscribe(message -> ((MessageChannel) message.getHeaders().getReplyChannel()).send(message));
    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());
    MessagingException messagingException = (MessagingException) event.getCause();
    assertSame(message, messagingException.getFailedMessage());
    assertEquals("Cannot correlate response - no pending reply for bar", messagingException.getMessage());

    message = new GenericMessage<String>("foo");
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertNull(event.getConnectionId());
    messagingException = (MessagingException) event.getCause();
    assertSame(message, messagingException.getFailedMessage());
    assertEquals("Cannot correlate response - no connection id", messagingException.getMessage());
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

private void testServerExceptionGuts(int port, AbstractServerConnectionFactory factory) throws Exception {
    ServerSocket ss = null;/*from w w  w  . ja v a  2 s  . c om*/
    try {
        ss = ServerSocketFactory.getDefault().createServerSocket(port);
    } catch (Exception e) {
        return; // skip this test, someone grabbed the port
    }
    final AtomicReference<TcpConnectionServerExceptionEvent> theEvent = new AtomicReference<TcpConnectionServerExceptionEvent>();
    final CountDownLatch latch = new CountDownLatch(1);
    factory.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set((TcpConnectionServerExceptionEvent) event);
            latch.countDown();
        }

        @Override
        public void publishEvent(Object event) {

        }

    });
    factory.setBeanName("sf");
    factory.registerListener(message -> false);
    Log logger = spy(TestUtils.getPropertyValue(factory, "logger", Log.class));
    doAnswer(new DoesNothing()).when(logger).error(anyString(), any(Throwable.class));
    new DirectFieldAccessor(factory).setPropertyValue("logger", logger);

    factory.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    String actual = theEvent.toString();
    assertThat(actual, containsString("cause=java.net.BindException"));
    assertThat(actual, containsString("source=" + "sf, port=" + port));

    ArgumentCaptor<String> reasonCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(logger).error(reasonCaptor.capture(), throwableCaptor.capture());
    assertThat(reasonCaptor.getValue(), startsWith("Error on Server"));
    assertThat(reasonCaptor.getValue(), endsWith("; port = " + port));
    assertThat(throwableCaptor.getValue(), instanceOf(BindException.class));
    ss.close();
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

@Test
public void testFailConnect() {
    TcpNetClientConnectionFactory ccf = new TcpNetClientConnectionFactory("junkjunk", 1234);
    final AtomicReference<ApplicationEvent> failEvent = new AtomicReference<ApplicationEvent>();
    ccf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override// w  w  w  .  j  av  a 2 s .c om
        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());
    }
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionFactoryTests.java

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

        @Override//from  w  ww.j a v  a2 s .c  om
        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(1, 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();
}

From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java

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

        @Override//from  w  ww  .  j a  v a 2  s .  c  om
        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();
    te.setCorePoolSize(3); // selector, reader, assembler
    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);

    final CountDownLatch readerLatch = new CountDownLatch(4); // 3 dataAvailable, 1 continuing
    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();
}

From source file:org.springframework.kafka.listener.KafkaMessageListenerContainerTests.java

private void testSeekGuts(Map<String, Object> props, String topic) throws Exception {
    logger.info("Start seek " + topic);
    DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(props);
    ContainerProperties containerProps = new ContainerProperties(topic11);
    final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(6));
    final AtomicBoolean seekInitial = new AtomicBoolean();
    final CountDownLatch idleLatch = new CountDownLatch(1);
    class Listener implements MessageListener<Integer, String>, ConsumerSeekAware {

        private ConsumerSeekCallback callback;

        private Thread registerThread;

        private Thread messageThread;

        @Override//from  ww w .j a  v  a 2  s .  c om
        public void onMessage(ConsumerRecord<Integer, String> data) {
            messageThread = Thread.currentThread();
            latch.get().countDown();
            if (latch.get().getCount() == 2 && !seekInitial.get()) {
                callback.seek(topic11, 0, 1);
                callback.seek(topic11, 1, 1);
            }
        }

        @Override
        public void registerSeekCallback(ConsumerSeekCallback callback) {
            this.callback = callback;
            this.registerThread = Thread.currentThread();
        }

        @Override
        public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {
            if (seekInitial.get()) {
                for (Entry<TopicPartition, Long> assignment : assignments.entrySet()) {
                    callback.seek(assignment.getKey().topic(), assignment.getKey().partition(),
                            assignment.getValue() - 1);
                }
            }
        }

        @Override
        public void onIdleContainer(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {
            for (Entry<TopicPartition, Long> assignment : assignments.entrySet()) {
                callback.seek(assignment.getKey().topic(), assignment.getKey().partition(),
                        assignment.getValue() - 1);
            }
            idleLatch.countDown();
        }

    }
    Listener messageListener = new Listener();
    containerProps.setMessageListener(messageListener);
    containerProps.setSyncCommits(true);
    containerProps.setAckMode(AckMode.RECORD);
    containerProps.setAckOnError(false);
    containerProps.setIdleEventInterval(60000L);

    KafkaMessageListenerContainer<Integer, String> container = new KafkaMessageListenerContainer<>(cf,
            containerProps);
    container.setBeanName("testRecordAcks");
    container.start();
    ContainerTestUtils.waitForAssignment(container, embeddedKafka.getPartitionsPerTopic());
    Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
    ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps);
    KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
    template.setDefaultTopic(topic11);
    template.sendDefault(0, 0, "foo");
    template.sendDefault(1, 0, "bar");
    template.sendDefault(0, 0, "baz");
    template.sendDefault(1, 0, "qux");
    template.flush();
    assertThat(latch.get().await(60, TimeUnit.SECONDS)).isTrue();
    container.stop();
    assertThat(messageListener.registerThread).isSameAs(messageListener.messageThread);

    // Now test initial seek of assigned partitions.
    latch.set(new CountDownLatch(2));
    seekInitial.set(true);
    container.start();
    assertThat(latch.get().await(60, TimeUnit.SECONDS)).isTrue();

    // Now seek on idle
    latch.set(new CountDownLatch(2));
    seekInitial.set(true);
    container.getContainerProperties().setIdleEventInterval(100L);
    final AtomicBoolean idleEventPublished = new AtomicBoolean();
    container.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
            // NOSONAR
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            idleEventPublished.set(true);
        }

    });
    assertThat(idleLatch.await(60, TimeUnit.SECONDS));
    assertThat(idleEventPublished.get()).isTrue();
    assertThat(latch.get().await(60, TimeUnit.SECONDS)).isTrue();
    container.stop();
    logger.info("Stop seek");
}