1/*  Copyright (c) 2000-2006 hamcrest.org
2 */
3package org.hamcrest.object;
4
5import org.hamcrest.Description;
6import org.hamcrest.Matcher;
7import org.hamcrest.Factory;
8import org.hamcrest.TypeSafeMatcher;
9
10import java.util.EventObject;
11
12
13/**
14 * Tests if the value is an event announced by a specific object.
15 */
16public class IsEventFrom extends TypeSafeMatcher<EventObject> {
17    private final Class eventClass;
18    private final Object source;
19
20    public IsEventFrom(Class eventClass, Object source) {
21        this.eventClass = eventClass;
22        this.source = source;
23    }
24
25    public boolean matchesSafely(EventObject item) {
26        return eventClass.isInstance(item)
27                && eventHasSameSource(item);
28    }
29
30    private boolean eventHasSameSource(EventObject ev) {
31        return ev.getSource() == source;
32    }
33
34    public void describeTo(Description description) {
35        description.appendText("an event of type ")
36                .appendText(eventClass.getName())
37                .appendText(" from ")
38                .appendValue(source);
39    }
40
41    /**
42     * Constructs an IsEventFrom Matcher that returns true for any object
43     * derived from <var>eventClass</var> announced by <var>source</var>.
44     */
45    @Factory
46    public static Matcher<EventObject> eventFrom(Class<? extends EventObject> eventClass, Object source) {
47        return new IsEventFrom(eventClass, source);
48    }
49
50    /**
51     * Constructs an IsEventFrom Matcher that returns true for any object
52     * derived from {@link java.util.EventObject} announced by <var>source
53     * </var>.
54     */
55    @Factory
56    public static Matcher<EventObject> eventFrom(Object source) {
57        return eventFrom(EventObject.class, source);
58    }
59}
60