AnnotationDrivenEventListenerTests.java 18.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
/*
 * Copyright 2002-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.event;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.event.test.AbstractIdentifiable;
import org.springframework.context.event.test.AnotherTestEvent;
import org.springframework.context.event.test.EventCollector;
import org.springframework.context.event.test.Identifiable;
import org.springframework.context.event.test.TestEvent;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

/**
 * @author Stephane Nicoll
 */
public class AnnotationDrivenEventListenerTests {

	@Rule
	public final ExpectedException thrown = ExpectedException.none();

	private ConfigurableApplicationContext context;

	private EventCollector eventCollector;

	private CountDownLatch countDownLatch; // 1 call by default

	@After
	public void closeContext() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	public void simpleEventJavaConfig() {
		load(TestEventListener.class);
		TestEvent event = new TestEvent(this, "test");
		TestEventListener listener = this.context.getBean(TestEventListener.class);
		this.eventCollector.assertNoEventReceived(listener);
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(listener, event);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void simpleEventXmlConfig() {
		this.context = new ClassPathXmlApplicationContext(
				"org/springframework/context/event/simple-event-configuration.xml");
		TestEvent event = new TestEvent(this, "test");
		TestEventListener listener = this.context.getBean(TestEventListener.class);
		this.eventCollector = getEventCollector(this.context);

		this.eventCollector.assertNoEventReceived(listener);
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(listener, event);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void metaAnnotationIsDiscovered() {
		load(MetaAnnotationListenerTestBean.class);

		MetaAnnotationListenerTestBean bean = context.getBean(MetaAnnotationListenerTestBean.class);
		this.eventCollector.assertNoEventReceived(bean);

		TestEvent event = new TestEvent();
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(bean, event);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void contextEventsAreReceived() {
		load(ContextEventListener.class);
		ContextEventListener listener = this.context.getBean(ContextEventListener.class);

		List<Object> events = this.eventCollector.getEvents(listener);
		assertEquals("Wrong number of initial context events", 1, events.size());
		assertEquals(ContextRefreshedEvent.class, events.get(0).getClass());

		this.context.stop();
		List<Object> eventsAfterStop = this.eventCollector.getEvents(listener);
		assertEquals("Wrong number of context events on shutdown", 2, eventsAfterStop.size());
		assertEquals(ContextStoppedEvent.class, eventsAfterStop.get(1).getClass());
		this.eventCollector.assertTotalEventsCount(2);
	}

	@Test
	public void methodSignatureNoEvent() {
		AnnotationConfigApplicationContext failingContext =
				new AnnotationConfigApplicationContext();
		failingContext.register(BasicConfiguration.class,
				InvalidMethodSignatureEventListener.class);

		thrown.expect(BeanInitializationException.class);
		thrown.expectMessage(InvalidMethodSignatureEventListener.class.getName());
		thrown.expectMessage("cannotBeCalled");
		failingContext.refresh();
	}

	@Test
	public void simpleReply() {
		load(TestEventListener.class, ReplyEventListener.class);
		AnotherTestEvent event = new AnotherTestEvent(this, "dummy");
		ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
		TestEventListener listener = this.context.getBean(TestEventListener.class);


		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertNoEventReceived(replyEventListener);
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(replyEventListener, event);
		this.eventCollector.assertEvent(listener, new TestEvent(replyEventListener, event.getId(), event.msg)); // reply
		this.eventCollector.assertTotalEventsCount(2);
	}

	@Test
	public void nullReplyIgnored() {
		load(TestEventListener.class, ReplyEventListener.class);
		AnotherTestEvent event = new AnotherTestEvent(this, null); // No response
		ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
		TestEventListener listener = this.context.getBean(TestEventListener.class);

		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertNoEventReceived(replyEventListener);
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(replyEventListener, event);
		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void eventListenerWorksWithInterfaceProxy() throws Exception {
		load(ProxyTestBean.class);

		SimpleService proxy = this.context.getBean(SimpleService.class);
		assertTrue("bean should be a proxy", proxy instanceof Advised);
		this.eventCollector.assertNoEventReceived(proxy.getId());

		TestEvent event = new TestEvent();
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(proxy.getId(), event);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void methodNotAvailableOnProxyIsDetected() throws Exception {
		thrown.expect(BeanInitializationException.class);
		thrown.expectMessage("handleIt2");
		load(InvalidProxyTestBean.class);
	}

	@Test
	public void eventListenerWorksWithCglibProxy() throws Exception {
		load(CglibProxyTestBean.class);

		CglibProxyTestBean proxy = this.context.getBean(CglibProxyTestBean.class);
		assertTrue("bean should be a cglib proxy", AopUtils.isCglibProxy(proxy));
		this.eventCollector.assertNoEventReceived(proxy.getId());

		TestEvent event = new TestEvent();
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(proxy.getId(), event);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void asyncProcessingApplied() throws InterruptedException {
		loadAsync(AsyncEventListener.class);
		String threadName = Thread.currentThread().getName();
		AnotherTestEvent event = new AnotherTestEvent(this, threadName);
		AsyncEventListener listener = this.context.getBean(AsyncEventListener.class);
		this.eventCollector.assertNoEventReceived(listener);

		this.context.publishEvent(event);

		countDownLatch.await(2, TimeUnit.SECONDS);
		this.eventCollector.assertEvent(listener, event);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void exceptionPropagated() {
		load(ExceptionEventListener.class);
		TestEvent event = new TestEvent(this, "fail");
		ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class);
		this.eventCollector.assertNoEventReceived(listener);
		try {
			this.context.publishEvent(event);
			fail("An exception should have thrown");
		}
		catch (IllegalStateException e) {
			assertEquals("Wrong exception", "Test exception", e.getMessage());
			this.eventCollector.assertEvent(listener, event);
			this.eventCollector.assertTotalEventsCount(1);
		}
	}

	@Test
	public void exceptionNotPropagatedWithAsync() throws InterruptedException {
		loadAsync(ExceptionEventListener.class);
		AnotherTestEvent event = new AnotherTestEvent(this, "fail");
		ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class);
		this.eventCollector.assertNoEventReceived(listener);

		this.context.publishEvent(event);
		countDownLatch.await(2, TimeUnit.SECONDS);

		this.eventCollector.assertEvent(listener, event);
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void listenerWithSimplePayload() {
		load(TestEventListener.class);
		TestEventListener listener = this.context.getBean(TestEventListener.class);

		this.eventCollector.assertNoEventReceived(listener);
		this.context.publishEvent("test");
		this.eventCollector.assertEvent(listener, "test");
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void listenerWithNonMatchingPayload() {
		load(TestEventListener.class);
		TestEventListener listener = this.context.getBean(TestEventListener.class);

		this.eventCollector.assertNoEventReceived(listener);
		this.context.publishEvent(123L);
		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertTotalEventsCount(0);
	}

	@Test
	public void replyWithPayload() {
		load(TestEventListener.class, ReplyEventListener.class);
		AnotherTestEvent event = new AnotherTestEvent(this, "String");
		ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
		TestEventListener listener = this.context.getBean(TestEventListener.class);


		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertNoEventReceived(replyEventListener);
		this.context.publishEvent(event);
		this.eventCollector.assertEvent(replyEventListener, event);
		this.eventCollector.assertEvent(listener, "String"); // reply
		this.eventCollector.assertTotalEventsCount(2);
	}

	@Test
	public void listenerWithGenericApplicationEvent() {
		load(GenericEventListener.class);
		GenericEventListener listener = this.context.getBean(GenericEventListener.class);

		this.eventCollector.assertNoEventReceived(listener);
		this.context.publishEvent("TEST");
		this.eventCollector.assertEvent(listener, "TEST");
		this.eventCollector.assertTotalEventsCount(1);
	}

	@Test
	public void conditionMatch() {
		long timestamp = System.currentTimeMillis();
		load(ConditionalEventListener.class);
		TestEvent event = new TestEvent(this, "OK");
		TestEventListener listener = this.context.getBean(ConditionalEventListener.class);
		this.eventCollector.assertNoEventReceived(listener);

		this.context.publishEvent(event);
		this.eventCollector.assertEvent(listener, event);
		this.eventCollector.assertTotalEventsCount(1);

		this.context.publishEvent("OK");
		this.eventCollector.assertEvent(listener, event, "OK");
		this.eventCollector.assertTotalEventsCount(2);

		this.context.publishEvent(timestamp);
		this.eventCollector.assertEvent(listener, event, "OK", timestamp);
		this.eventCollector.assertTotalEventsCount(3);
	}

	@Test
	public void conditionDoesNotMatch() {
		long maxLong = Long.MAX_VALUE;
		load(ConditionalEventListener.class);
		TestEvent event = new TestEvent(this, "KO");
		TestEventListener listener = this.context.getBean(ConditionalEventListener.class);
		this.eventCollector.assertNoEventReceived(listener);

		this.context.publishEvent(event);
		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertTotalEventsCount(0);

		this.context.publishEvent("KO");
		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertTotalEventsCount(0);

		this.context.publishEvent(maxLong);
		this.eventCollector.assertNoEventReceived(listener);
		this.eventCollector.assertTotalEventsCount(0);
	}

	@Test
	public void orderedListeners() {
		load(OrderedTestListener.class);
		OrderedTestListener listener = this.context.getBean(OrderedTestListener.class);

		assertTrue(listener.order.isEmpty());
		this.context.publishEvent("whatever");
		assertThat(listener.order, contains("first", "second", "third"));
	}

	private void load(Class<?>... classes) {
		List<Class<?>> allClasses = new ArrayList<>();
		allClasses.add(BasicConfiguration.class);
		allClasses.addAll(Arrays.asList(classes));
		doLoad(allClasses.toArray(new Class<?>[allClasses.size()]));
	}

	private void loadAsync(Class<?>... classes) {
		List<Class<?>> allClasses = new ArrayList<>();
		allClasses.add(AsyncConfiguration.class);
		allClasses.addAll(Arrays.asList(classes));
		doLoad(allClasses.toArray(new Class<?>[allClasses.size()]));
	}

	private void doLoad(Class<?>... classes) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(classes);
		this.eventCollector = ctx.getBean(EventCollector.class);
		this.countDownLatch = ctx.getBean(CountDownLatch.class);
		this.context = ctx;
	}

	private EventCollector getEventCollector(ConfigurableApplicationContext context) {
		return context.getBean(EventCollector.class);
	}


	@Configuration
	static class BasicConfiguration {

		@Bean
		public EventCollector eventCollector() {
			return new EventCollector();
		}

		@Bean
		public CountDownLatch testCountDownLatch() {
			return new CountDownLatch(1);
		}

	}

	static abstract class AbstractTestEventListener extends AbstractIdentifiable {

		@Autowired
		private EventCollector eventCollector;

		protected void collectEvent(Object content) {
			this.eventCollector.addEvent(this, content);
		}

	}

	@Component
	static class TestEventListener extends AbstractTestEventListener {

		@EventListener
		public void handle(TestEvent event) {
			collectEvent(event);
		}

		@EventListener
		public void handleString(String content) {
			collectEvent(content);
		}

	}

	@EventListener
	@Target(ElementType.METHOD)
	@Retention(RetentionPolicy.RUNTIME)
	@interface FooListener {
	}

	@Component
	static class MetaAnnotationListenerTestBean extends AbstractTestEventListener {

		@FooListener
		public void handleIt(TestEvent event) {
			collectEvent(event);
		}
	}

	@Component
	static class ContextEventListener extends AbstractTestEventListener {

		@EventListener
		public void handleContextEvent(ApplicationContextEvent event) {
			collectEvent(event);
		}

	}

	@Component
	static class InvalidMethodSignatureEventListener {

		@EventListener
		public void cannotBeCalled(String s, Integer what) {
		}
	}

	@Component
	static class ReplyEventListener extends AbstractTestEventListener {

		@EventListener
		public Object handle(AnotherTestEvent event) {
			collectEvent(event);
			if (event.msg == null) {
				return null;
			}
			else if (event.msg.equals("String")) {
				return event.msg;
			}
			else {
				return new TestEvent(this, event.getId(), event.msg);
			}
		}

	}

	@Component
	static class ExceptionEventListener extends AbstractTestEventListener {

		@Autowired
		private CountDownLatch countDownLatch;

		@EventListener
		public void handle(TestEvent event) {
			collectEvent(event);
			if ("fail".equals(event.msg)) {
				throw new IllegalStateException("Test exception");
			}
		}

		@EventListener
		@Async
		public void handleAsync(AnotherTestEvent event) {
			collectEvent(event);
			if ("fail".equals(event.msg)) {
				countDownLatch.countDown();
				throw new IllegalStateException("Test exception");
			}
		}
	}

	@Configuration
	@Import(BasicConfiguration.class)
	@EnableAsync(proxyTargetClass = true)
	static class AsyncConfiguration {
	}

	@Component
	static class AsyncEventListener extends AbstractTestEventListener {

		@Autowired
		private CountDownLatch countDownLatch;

		@EventListener
		@Async
		public void handleAsync(AnotherTestEvent event) {
			assertTrue(!Thread.currentThread().getName().equals(event.msg));
			collectEvent(event);
			countDownLatch.countDown();
		}
	}

	interface SimpleService extends Identifiable {

		@EventListener
		void handleIt(TestEvent event);

	}

	@Component
	@Scope(proxyMode = ScopedProxyMode.INTERFACES)
	static class ProxyTestBean extends AbstractIdentifiable implements SimpleService {

		@Autowired
		private EventCollector eventCollector;

		@Override
		public void handleIt(TestEvent event) {
			eventCollector.addEvent(this, event);
		}
	}

	@Component
	@Scope(proxyMode = ScopedProxyMode.INTERFACES)
	static class InvalidProxyTestBean extends ProxyTestBean {

		@EventListener // does not exist on any interface so it should fail
		public void handleIt2(TestEvent event) {
		}
	}

	@Component
	@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
	static class CglibProxyTestBean extends AbstractTestEventListener {

		@EventListener
		public void handleIt(TestEvent event) {
			collectEvent(event);
		}
	}

	@Component
	static class GenericEventListener extends AbstractTestEventListener {

		@EventListener
		public void handleString(PayloadApplicationEvent<String> event) {
			collectEvent(event.getPayload());
		}
	}

	@Component
	static class ConditionalEventListener extends TestEventListener {

		@EventListener(condition = "'OK'.equals(#root.event.msg)")
		@Override
		public void handle(TestEvent event) {
			super.handle(event);
		}

		@Override
		@EventListener(condition = "'OK'.equals(#content)")
		public void handleString(String content) {
			super.handleString(content);
		}

		@EventListener(condition = "#root.event.timestamp > #p0")
		public void handleTimestamp(Long timestamp) {
			collectEvent(timestamp);
		}

	}

	@Component
	static class OrderedTestListener extends TestEventListener {

		public final List<String> order = new ArrayList<>();

		@EventListener
		@Order(50)
		public void handleThird(String payload) {
			order.add("third");
		}

		@EventListener
		@Order(-50)
		public void handleFirst(String payload) {
			order.add("first");
		}

		@EventListener
		public void handleSecond(String payload) {
			order.add("second");
		}
	}

}