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 * http://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.configuration2.event;
18
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.LinkedList;
22 import java.util.List;
23
24 /**
25 * <p>
26 * A base class for objects that can generate configuration events.
27 * </p>
28 * <p>
29 * This class implements functionality for managing a set of event listeners that can be notified when an event occurs.
30 * It can be extended by configuration classes that support the event mechanism. In this case these classes only need to
31 * call the {@code fireEvent()} method when an event is to be delivered to the registered listeners.
32 * </p>
33 * <p>
34 * Adding and removing event listeners can happen concurrently to manipulations on a configuration that cause events.
35 * The operations are synchronized.
36 * </p>
37 * <p>
38 * With the {@code detailEvents} property the number of detail events can be controlled. Some methods in configuration
39 * classes are implemented in a way that they call other methods that can generate their own events. One example is the
40 * {@code setProperty()} method that can be implemented as a combination of {@code clearProperty()} and
41 * {@code addProperty()}. With {@code detailEvents} set to <strong>true</strong>, all involved methods will generate events (i.e.
42 * listeners will receive property set events, property clear events, and property add events). If this mode is turned
43 * off (which is the default), detail events are suppressed, so only property set events will be received. Note that the
44 * number of received detail events may differ for different configuration implementations.
45 * {@link org.apache.commons.configuration2.BaseHierarchicalConfiguration BaseHierarchicalConfiguration} for instance
46 * has a custom implementation of {@code setProperty()}, which does not generate any detail events.
47 * </p>
48 * <p>
49 * In addition to "normal" events, error events are supported. Such events signal an internal problem that
50 * occurred during access of properties. They are handled via the regular {@link EventListener} interface, but there are
51 * special event types defined by {@link ConfigurationErrorEvent}. The {@code fireError()} method can be used by derived
52 * classes to send notifications about errors to registered observers.
53 * </p>
54 *
55 * @since 1.3
56 */
57 public class BaseEventSource implements EventSource {
58
59 /** The list for managing registered event listeners. */
60 private EventListenerList eventListeners;
61
62 /** A lock object for guarding access to the detail events counter. */
63 private final Object lockDetailEventsCount = new Object();
64
65 /** A counter for the detail events. */
66 private int detailEvents;
67
68 /**
69 * Creates a new instance of {@code BaseEventSource}.
70 */
71 public BaseEventSource() {
72 initListeners();
73 }
74
75 @Override
76 public <T extends Event> void addEventListener(final EventType<T> eventType, final EventListener<? super T> listener) {
77 eventListeners.addEventListener(eventType, listener);
78 }
79
80 /**
81 * Helper method for checking the current counter for detail events. This method checks whether the counter is greater
82 * than the passed in limit.
83 *
84 * @param limit the limit to be compared to
85 * @return <strong>true</strong> if the counter is greater than the limit, <strong>false</strong> otherwise
86 */
87 private boolean checkDetailEvents(final int limit) {
88 synchronized (lockDetailEventsCount) {
89 return detailEvents > limit;
90 }
91 }
92
93 /**
94 * Removes all registered error listeners.
95 *
96 * @since 1.4
97 */
98 public void clearErrorListeners() {
99 eventListeners.getRegistrationsForSuperType(ConfigurationErrorEvent.ANY).forEach(eventListeners::removeEventListener);
100 }
101
102 /**
103 * Removes all registered event listeners.
104 */
105 public void clearEventListeners() {
106 eventListeners.clear();
107 }
108
109 /**
110 * Overrides the {@code clone()} method to correctly handle so far registered event listeners. This implementation ensures that the clone will have empty
111 * event listener lists, i.e. the listeners registered at an {@code BaseEventSource} object will not be copied.
112 *
113 * @return the cloned object
114 * @throws CloneNotSupportedException if the object's class does not support the {@code Cloneable} interface. Subclasses that override the {@code clone}
115 * method can also throw this exception to indicate that an instance cannot be cloned.
116 * @since 1.4
117 */
118 @Override
119 protected Object clone() throws CloneNotSupportedException {
120 final BaseEventSource copy = (BaseEventSource) super.clone();
121 copy.initListeners();
122 return copy;
123 }
124
125 /**
126 * Copies all event listener registrations maintained by this object to the specified {@code BaseEventSource} object.
127 *
128 * @param source the target source for the copy operation (must not be <strong>null</strong>)
129 * @throws IllegalArgumentException if the target source is <strong>null</strong>
130 * @since 2.0
131 */
132 public void copyEventListeners(final BaseEventSource source) {
133 if (source == null) {
134 throw new IllegalArgumentException("Target event source must not be null!");
135 }
136 source.eventListeners.addAll(eventListeners);
137 }
138
139 /**
140 * Creates a {@code ConfigurationErrorEvent} object based on the passed in parameters. This is called by
141 * {@code fireError()} if it decides that an event needs to be generated.
142 *
143 * @param type the event's type
144 * @param opType the operation type related to this error
145 * @param propName the name of the affected property (can be <strong>null</strong>)
146 * @param propValue the value of the affected property (can be <strong>null</strong>)
147 * @param ex the {@code Throwable} object that caused this error event
148 * @return the event object
149 */
150 protected ConfigurationErrorEvent createErrorEvent(final EventType<? extends ConfigurationErrorEvent> type, final EventType<?> opType,
151 final String propName, final Object propValue, final Throwable ex) {
152 return new ConfigurationErrorEvent(this, type, opType, propName, propValue, ex);
153 }
154
155 /**
156 * Creates a {@code ConfigurationEvent} object based on the passed in parameters. This method is called by
157 * {@code fireEvent()} if it decides that an event needs to be generated.
158 *
159 * @param type the event's type
160 * @param propName the name of the affected property (can be <strong>null</strong>)
161 * @param propValue the value of the affected property (can be <strong>null</strong>)
162 * @param before the before update flag
163 * @param <T> the type of the event to be created
164 * @return the newly created event object
165 */
166 protected <T extends ConfigurationEvent> ConfigurationEvent createEvent(final EventType<T> type, final String propName, final Object propValue,
167 final boolean before) {
168 return new ConfigurationEvent(this, type, propName, propValue, before);
169 }
170
171 /**
172 * Creates an error event object and delivers it to all registered error listeners of a matching type.
173 *
174 * @param eventType the event's type
175 * @param operationType the type of the failed operation
176 * @param propertyName the name of the affected property (can be <strong>null</strong>)
177 * @param propertyValue the value of the affected property (can be <strong>null</strong>)
178 * @param cause the {@code Throwable} object that caused this error event
179 * @param <T> the event type
180 */
181 public <T extends ConfigurationErrorEvent> void fireError(final EventType<T> eventType, final EventType<?> operationType, final String propertyName,
182 final Object propertyValue, final Throwable cause) {
183 final EventListenerList.EventListenerIterator<T> iterator = eventListeners.getEventListenerIterator(eventType);
184 if (iterator.hasNext()) {
185 final ConfigurationErrorEvent event = createErrorEvent(eventType, operationType, propertyName, propertyValue, cause);
186 while (iterator.hasNext()) {
187 iterator.invokeNext(event);
188 }
189 }
190 }
191
192 /**
193 * Creates an event object and delivers it to all registered event listeners. The method checks first if sending an
194 * event is allowed (making use of the {@code detailEvents} property), and if listeners are registered.
195 *
196 * @param type the event's type
197 * @param propName the name of the affected property (can be <strong>null</strong>)
198 * @param propValue the value of the affected property (can be <strong>null</strong>)
199 * @param before the before update flag
200 * @param <T> the type of the event to be fired
201 */
202 protected <T extends ConfigurationEvent> void fireEvent(final EventType<T> type, final String propName, final Object propValue, final boolean before) {
203 if (checkDetailEvents(-1)) {
204 final EventListenerList.EventListenerIterator<T> it = eventListeners.getEventListenerIterator(type);
205 if (it.hasNext()) {
206 final ConfigurationEvent event = createEvent(type, propName, propValue, before);
207 while (it.hasNext()) {
208 it.invokeNext(event);
209 }
210 }
211 }
212 }
213
214 /**
215 * Gets a list with all {@code EventListenerRegistrationData} objects currently contained for this event source. This
216 * method allows access to all registered event listeners, independent on their type.
217 *
218 * @return a list with information about all registered event listeners
219 */
220 public List<EventListenerRegistrationData<?>> getEventListenerRegistrations() {
221 return eventListeners.getRegistrations();
222 }
223
224 /**
225 * Gets a collection with all event listeners of the specified event type that are currently registered at this
226 * object.
227 *
228 * @param eventType the event type object
229 * @param <T> the event type
230 * @return a collection with the event listeners of the specified event type (this collection is a snapshot of the
231 * currently registered listeners; it cannot be manipulated)
232 */
233 public <T extends Event> Collection<EventListener<? super T>> getEventListeners(final EventType<T> eventType) {
234 final List<EventListener<? super T>> result = new LinkedList<>();
235 eventListeners.getEventListeners(eventType).forEach(result::add);
236 return Collections.unmodifiableCollection(result);
237 }
238
239 /**
240 * Initializes the collections for storing registered event listeners.
241 */
242 private void initListeners() {
243 eventListeners = new EventListenerList();
244 }
245
246 /**
247 * Returns a flag whether detail events are enabled.
248 *
249 * @return a flag if detail events are generated
250 */
251 public boolean isDetailEvents() {
252 return checkDetailEvents(0);
253 }
254
255 @Override
256 public <T extends Event> boolean removeEventListener(final EventType<T> eventType, final EventListener<? super T> listener) {
257 return eventListeners.removeEventListener(eventType, listener);
258 }
259
260 /**
261 * Determines whether detail events should be generated. If enabled, some methods can generate multiple update events.
262 * Note that this method records the number of calls, i.e. if for instance {@code setDetailEvents(false)} was called
263 * three times, you will have to invoke the method as often to enable the details.
264 *
265 * @param enable a flag if detail events should be enabled or disabled
266 */
267 public void setDetailEvents(final boolean enable) {
268 synchronized (lockDetailEventsCount) {
269 if (enable) {
270 detailEvents++;
271 } else {
272 detailEvents--;
273 }
274 }
275 }
276 }