Search in sources :

Example 6 with ApplicationEvent

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

the class ConnectionEventTests method testServerExceptionGuts.

private void testServerExceptionGuts(AbstractServerConnectionFactory factory) throws Exception {
    ServerSocket ss = null;
    try {
        ss = ServerSocketFactory.getDefault().createServerSocket(0);
    } catch (Exception e) {
        fail("Failed to get a server socket");
    }
    factory.setPort(ss.getLocalPort());
    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));
    doNothing().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=" + factory.getPort()));
    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 = " + factory.getPort()));
    assertThat(throwableCaptor.getValue(), instanceOf(BindException.class));
    ss.close();
}
Also used : Log(org.apache.commons.logging.Log) ApplicationEvent(org.springframework.context.ApplicationEvent) BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessagingException(org.springframework.messaging.MessagingException) BindException(java.net.BindException) UnknownHostException(java.net.UnknownHostException) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor)

Example 7 with ApplicationEvent

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

the class RedisQueueMessageDrivenEndpointTests method testInt3196Recovery.

@Test
@RedisAvailable
@Ignore("JedisConnectionFactory doesn't support proper 'destroy()' and allows to create new fresh Redis connection")
public void testInt3196Recovery() throws Exception {
    String queueName = "test.si.Int3196Recovery";
    QueueChannel channel = new QueueChannel();
    final List<ApplicationEvent> exceptionEvents = new ArrayList<>();
    final CountDownLatch exceptionsLatch = new CountDownLatch(2);
    RedisQueueMessageDrivenEndpoint endpoint = new RedisQueueMessageDrivenEndpoint(queueName, this.connectionFactory);
    endpoint.setBeanFactory(Mockito.mock(BeanFactory.class));
    endpoint.setApplicationEventPublisher(event -> {
        exceptionEvents.add((ApplicationEvent) event);
        exceptionsLatch.countDown();
    });
    endpoint.setOutputChannel(channel);
    endpoint.setReceiveTimeout(100);
    endpoint.setRecoveryInterval(200);
    endpoint.afterPropertiesSet();
    endpoint.start();
    waitListening(endpoint);
    ((DisposableBean) this.connectionFactory).destroy();
    assertTrue(exceptionsLatch.await(10, TimeUnit.SECONDS));
    for (ApplicationEvent exceptionEvent : exceptionEvents) {
        assertThat(exceptionEvent, Matchers.instanceOf(RedisExceptionEvent.class));
        assertSame(endpoint, exceptionEvent.getSource());
        assertThat(((IntegrationEvent) exceptionEvent).getCause().getClass(), Matchers.isIn(Arrays.asList(RedisSystemException.class, RedisConnectionFailureException.class)));
    }
    ((InitializingBean) this.connectionFactory).afterPropertiesSet();
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    redisTemplate.setConnectionFactory(this.getConnectionFactoryForTest());
    redisTemplate.setEnableDefaultSerializer(false);
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.afterPropertiesSet();
    String payload = "testing";
    redisTemplate.boundListOps(queueName).leftPush(payload);
    Message<?> receive = channel.receive(10000);
    assertNotNull(receive);
    assertEquals(payload, receive.getPayload());
    endpoint.stop();
}
Also used : StringRedisTemplate(org.springframework.data.redis.core.StringRedisTemplate) RedisTemplate(org.springframework.data.redis.core.RedisTemplate) QueueChannel(org.springframework.integration.channel.QueueChannel) JdkSerializationRedisSerializer(org.springframework.data.redis.serializer.JdkSerializationRedisSerializer) ApplicationEvent(org.springframework.context.ApplicationEvent) ArrayList(java.util.ArrayList) RedisExceptionEvent(org.springframework.integration.redis.event.RedisExceptionEvent) CountDownLatch(java.util.concurrent.CountDownLatch) StringRedisSerializer(org.springframework.data.redis.serializer.StringRedisSerializer) DisposableBean(org.springframework.beans.factory.DisposableBean) BeanFactory(org.springframework.beans.factory.BeanFactory) IntegrationEvent(org.springframework.integration.events.IntegrationEvent) InitializingBean(org.springframework.beans.factory.InitializingBean) RedisAvailable(org.springframework.integration.redis.rules.RedisAvailable) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 8 with ApplicationEvent

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

the class ApplicationEventListeningMessageProducerTests method testInt2935CheckRetrieverCache.

@Test
@SuppressWarnings({ "unchecked", "serial" })
public void testInt2935CheckRetrieverCache() {
    GenericApplicationContext ctx = TestUtils.createTestApplicationContext();
    ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory();
    QueueChannel channel = new QueueChannel();
    ApplicationEventListeningMessageProducer listenerMessageProducer = new ApplicationEventListeningMessageProducer();
    listenerMessageProducer.setOutputChannel(channel);
    listenerMessageProducer.setEventTypes(TestApplicationEvent2.class);
    beanFactory.registerSingleton("testListenerMessageProducer", listenerMessageProducer);
    AtomicInteger listenerCounter = new AtomicInteger();
    beanFactory.registerSingleton("testListener", new TestApplicationListener(listenerCounter));
    ctx.refresh();
    ApplicationEventMulticaster multicaster = ctx.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
    Map<?, ?> retrieverCache = TestUtils.getPropertyValue(multicaster, "retrieverCache", Map.class);
    ctx.publishEvent(new TestApplicationEvent1());
    /*
		 *  Previously, the retrieverCache grew unnecessarily; the adapter was added to the cache for each event type,
		 *  event if not supported.
		 */
    assertEquals(2, retrieverCache.size());
    for (Map.Entry<?, ?> entry : retrieverCache.entrySet()) {
        Class<? extends ApplicationEvent> event = TestUtils.getPropertyValue(entry.getKey(), "eventType.resolved", Class.class);
        assertThat(event, Matchers.is(Matchers.isOneOf(ContextRefreshedEvent.class, TestApplicationEvent1.class)));
        Set<?> listeners = TestUtils.getPropertyValue(entry.getValue(), "applicationListenerBeans", Set.class);
        assertEquals(1, listeners.size());
        assertEquals("testListener", listeners.iterator().next());
    }
    TestApplicationEvent2 event2 = new TestApplicationEvent2();
    ctx.publishEvent(event2);
    assertEquals(3, retrieverCache.size());
    for (Map.Entry<?, ?> entry : retrieverCache.entrySet()) {
        Class<?> event = TestUtils.getPropertyValue(entry.getKey(), "eventType.resolved", Class.class);
        if (TestApplicationEvent2.class.isAssignableFrom(event)) {
            Set<?> listeners = TestUtils.getPropertyValue(entry.getValue(), "applicationListenerBeans", Set.class);
            assertEquals(2, listeners.size());
            for (Object listener : listeners) {
                assertThat((String) listener, Matchers.is(Matchers.isOneOf("testListenerMessageProducer", "testListener")));
            }
            break;
        }
    }
    ctx.publishEvent(new ApplicationEvent("Some event") {
    });
    assertEquals(4, listenerCounter.get());
    final Message<?> receive = channel.receive(10);
    assertNotNull(receive);
    assertSame(event2, receive.getPayload());
    assertNull(channel.receive(1));
    ctx.close();
}
Also used : SimpleApplicationEventMulticaster(org.springframework.context.event.SimpleApplicationEventMulticaster) ApplicationEventMulticaster(org.springframework.context.event.ApplicationEventMulticaster) QueueChannel(org.springframework.integration.channel.QueueChannel) ApplicationEvent(org.springframework.context.ApplicationEvent) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) Test(org.junit.Test)

Example 9 with ApplicationEvent

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

the class ResourceReaderRepositoryInitializerUnitTests method emitsRepositoriesPopulatedEventIfPublisherConfigured.

// DATACMNS-224
@Test
public void emitsRepositoriesPopulatedEventIfPublisherConfigured() throws Exception {
    RepositoryPopulator populator = setUpReferenceAndInititalize(new User(), publisher);
    ApplicationEvent event = new RepositoriesPopulatedEvent(populator, repositories);
    verify(publisher, times(1)).publishEvent(event);
}
Also used : User(org.springframework.data.repository.sample.User) ApplicationEvent(org.springframework.context.ApplicationEvent) Test(org.junit.Test)

Example 10 with ApplicationEvent

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

the class DelegatingApplicationListenerTests method setup.

@BeforeEach
public void setup() {
    this.event = new ApplicationEvent(this) {
    };
    this.listener = new DelegatingApplicationListener();
    this.listener.addListener(this.delegate);
}
Also used : ApplicationEvent(org.springframework.context.ApplicationEvent) BeforeEach(org.junit.jupiter.api.BeforeEach)

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