View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.event;
18  
19  import static org.apache.commons.lang3.LangAssertions.assertIllegalArgumentException;
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertFalse;
22  import static org.junit.jupiter.api.Assertions.assertNotNull;
23  import static org.junit.jupiter.api.Assertions.assertThrows;
24  import static org.junit.jupiter.api.Assertions.assertTrue;
25  
26  import java.beans.PropertyChangeEvent;
27  import java.beans.PropertyChangeListener;
28  import java.beans.VetoableChangeListener;
29  import java.lang.reflect.Constructor;
30  import java.lang.reflect.InvocationHandler;
31  import java.lang.reflect.Method;
32  import java.lang.reflect.Modifier;
33  import java.lang.reflect.Proxy;
34  import java.util.Date;
35  import java.util.Map;
36  import java.util.TreeMap;
37  
38  import javax.naming.event.ObjectChangeListener;
39  
40  import org.apache.commons.lang3.AbstractLangTest;
41  import org.junit.jupiter.api.Test;
42  
43  /**
44   */
45  class EventUtilsTest extends AbstractLangTest {
46      public static class EventCounter {
47          private int count;
48  
49          public void eventOccurred() {
50              count++;
51          }
52  
53          public int getCount() {
54              return count;
55          }
56      }
57  
58      public static class EventCounterWithEvent {
59          private int count;
60  
61          public void eventOccurred(final PropertyChangeEvent e) {
62              count++;
63          }
64  
65          public int getCount() {
66              return count;
67          }
68      }
69  
70      private static final class EventCountingInvocationHandler implements InvocationHandler {
71  
72          private final Map<String, Integer> eventCounts = new TreeMap<>();
73  
74          public <L> L createListener(final Class<L> listenerType) {
75              return listenerType.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { listenerType }, this));
76          }
77  
78          public int getEventCount(final String eventName) {
79              final Integer count = eventCounts.get(eventName);
80              return count == null ? 0 : count.intValue();
81          }
82  
83          @Override
84          public Object invoke(final Object proxy, final Method method, final Object[] args) {
85              final Integer count = eventCounts.get(method.getName());
86              if (count == null) {
87                  eventCounts.put(method.getName(), Integer.valueOf(1));
88              } else {
89                  eventCounts.put(method.getName(), Integer.valueOf(count.intValue() + 1));
90              }
91              return null;
92          }
93      }
94  
95      public static class ExceptionEventSource {
96          public void addPropertyChangeListener(final PropertyChangeListener listener) {
97              throw new RuntimeException();
98          }
99      }
100 
101     public interface MultipleEventListener {
102         void event1(PropertyChangeEvent e);
103 
104         void event2(PropertyChangeEvent e);
105     }
106 
107     public static class MultipleEventSource {
108         private final EventListenerSupport<MultipleEventListener> listeners = EventListenerSupport.create(MultipleEventListener.class);
109 
110         public void addMultipleEventListener(final MultipleEventListener listener) {
111             listeners.addListener(listener);
112         }
113     }
114 
115     public static class PropertyChangeSource {
116         private final EventListenerSupport<PropertyChangeListener> listeners = EventListenerSupport.create(PropertyChangeListener.class);
117 
118         private String property;
119 
120         public void addPropertyChangeListener(final PropertyChangeListener listener) {
121             listeners.addListener(listener);
122         }
123 
124         protected void addVetoableChangeListener(final VetoableChangeListener listener) {
125             // Do nothing!
126         }
127 
128         public void removePropertyChangeListener(final PropertyChangeListener listener) {
129             listeners.removeListener(listener);
130         }
131 
132         public void setProperty(final String property) {
133             final String oldValue = this.property;
134             this.property = property;
135             listeners.fire().propertyChange(new PropertyChangeEvent(this, "property", oldValue, property));
136         }
137     }
138 
139     @Test
140     void testAddEventListener() {
141         final PropertyChangeSource src = new PropertyChangeSource();
142         final EventCountingInvocationHandler handler = new EventCountingInvocationHandler();
143         final PropertyChangeListener listener = handler.createListener(PropertyChangeListener.class);
144         assertEquals(0, handler.getEventCount("propertyChange"));
145         EventUtils.addEventListener(src, PropertyChangeListener.class, listener);
146         assertEquals(0, handler.getEventCount("propertyChange"));
147         src.setProperty("newValue");
148         assertEquals(1, handler.getEventCount("propertyChange"));
149     }
150 
151     @Test
152     void testAddEventListenerThrowsException() {
153         final ExceptionEventSource src = new ExceptionEventSource();
154         assertThrows(RuntimeException.class, () -> EventUtils.addEventListener(src, PropertyChangeListener.class, e -> {
155             // Do nothing!
156         }));
157     }
158 
159     @Test
160     void testAddEventListenerWithNoAddMethod() {
161         final PropertyChangeSource src = new PropertyChangeSource();
162         final EventCountingInvocationHandler handler = new EventCountingInvocationHandler();
163         final ObjectChangeListener listener = handler.createListener(ObjectChangeListener.class);
164         final IllegalArgumentException e = assertIllegalArgumentException(() -> EventUtils.addEventListener(src, ObjectChangeListener.class, listener));
165         assertEquals("Unable to add listener for class " + src.getClass().getName() + " and public add" + ObjectChangeListener.class.getSimpleName()
166                 + " method which takes a parameter of type " + ObjectChangeListener.class.getName() + ".", e.getMessage());
167     }
168 
169     @Test
170     void testAddEventListenerWithPrivateAddMethod() {
171         final PropertyChangeSource src = new PropertyChangeSource();
172         final EventCountingInvocationHandler handler = new EventCountingInvocationHandler();
173         final VetoableChangeListener listener = handler.createListener(VetoableChangeListener.class);
174         final IllegalArgumentException e = assertIllegalArgumentException(() -> EventUtils.addEventListener(src, VetoableChangeListener.class, listener));
175         assertEquals("Unable to add listener for class " + src.getClass().getName() + " and public add" + VetoableChangeListener.class.getSimpleName()
176                 + " method which takes a parameter of type " + VetoableChangeListener.class.getName() + ".", e.getMessage());
177     }
178 
179     @Test
180     void testBindEventsToMethod() {
181         final PropertyChangeSource src = new PropertyChangeSource();
182         final EventCounter counter = new EventCounter();
183         EventUtils.bindEventsToMethod(counter, "eventOccurred", src, PropertyChangeListener.class);
184         assertEquals(0, counter.getCount());
185         src.setProperty("newValue");
186         assertEquals(1, counter.getCount());
187     }
188 
189     @Test
190     void testBindEventsToMethodWithEvent() {
191         final PropertyChangeSource src = new PropertyChangeSource();
192         final EventCounterWithEvent counter = new EventCounterWithEvent();
193         EventUtils.bindEventsToMethod(counter, "eventOccurred", src, PropertyChangeListener.class);
194         assertEquals(0, counter.getCount());
195         src.setProperty("newValue");
196         assertEquals(1, counter.getCount());
197     }
198 
199     @Test
200     void testBindFilteredEventsToMethod() {
201         final MultipleEventSource src = new MultipleEventSource();
202         final EventCounter counter = new EventCounter();
203         EventUtils.bindEventsToMethod(counter, "eventOccurred", src, MultipleEventListener.class, "event1");
204         assertEquals(0, counter.getCount());
205         src.listeners.fire().event1(new PropertyChangeEvent(new Date(), "Day", Integer.valueOf(0), Integer.valueOf(1)));
206         assertEquals(1, counter.getCount());
207         src.listeners.fire().event2(new PropertyChangeEvent(new Date(), "Day", Integer.valueOf(1), Integer.valueOf(2)));
208         assertEquals(1, counter.getCount());
209     }
210 
211     @Test
212     void testConstructor() {
213         assertNotNull(new EventUtils());
214         final Constructor<?>[] cons = EventUtils.class.getDeclaredConstructors();
215         assertEquals(1, cons.length);
216         assertTrue(Modifier.isPublic(cons[0].getModifiers()));
217         assertTrue(Modifier.isPublic(EventUtils.class.getModifiers()));
218         assertFalse(Modifier.isFinal(EventUtils.class.getModifiers()));
219     }
220 }