    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *     http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.configuration2.event;
    018
    019import java.util.Collection;
    020import java.util.Collections;
    021import java.util.LinkedList;
    022import java.util.List;
    023
    024/**
    025 * <p>
    026 * A base class for objects that can generate configuration events.
    027 * </p>
    028 * <p>
    029 * This class implements functionality for managing a set of event listeners that can be notified when an event occurs.
    030 * It can be extended by configuration classes that support the event mechanism. In this case these classes only need to
    031 * call the {@code fireEvent()} method when an event is to be delivered to the registered listeners.
    032 * </p>
    033 * <p>
    034 * Adding and removing event listeners can happen concurrently to manipulations on a configuration that cause events.
    035 * The operations are synchronized.
    036 * </p>
    037 * <p>
    038 * With the {@code detailEvents} property the number of detail events can be controlled. Some methods in configuration
    039 * classes are implemented in a way that they call other methods that can generate their own events. One example is the
    040 * {@code setProperty()} method that can be implemented as a combination of {@code clearProperty()} and
    041 * {@code addProperty()}. With {@code detailEvents} set to <b>true</b>, all involved methods will generate events (i.e.
    042 * listeners will receive property set events, property clear events, and property add events). If this mode is turned
    043 * off (which is the default), detail events are suppressed, so only property set events will be received. Note that the
    044 * number of received detail events may differ for different configuration implementations.
    045 * {@link org.apache.commons.configuration2.BaseHierarchicalConfiguration BaseHierarchicalConfiguration} for instance
    046 * has a custom implementation of {@code setProperty()}, which does not generate any detail events.
    047 * </p>
    048 * <p>
    049 * In addition to &quot;normal&quot; events, error events are supported. Such events signal an internal problem that
    050 * occurred during access of properties. They are handled via the regular {@link EventListener} interface, but there are
    051 * special event types defined by {@link ConfigurationErrorEvent}. The {@code fireError()} method can be used by derived
    052 * classes to send notifications about errors to registered observers.
    053 * </p>
    054 *
    055 * @since 1.3
    056 */
    057public class BaseEventSource implements EventSource {
    058    /** The list for managing registered event listeners. */
    059    private EventListenerList eventListeners;
    060
    061    /** A lock object for guarding access to the detail events counter. */
    062    private final Object lockDetailEventsCount = new Object();
    063
    064    /** A counter for the detail events. */
    065    private int detailEvents;
    066
    067    /**
    068     * Creates a new instance of {@code BaseEventSource}.
    069     */
    070    public BaseEventSource() {
    071        initListeners();
    072    }
    073
    074    /**
    075     * Returns a collection with all event listeners of the specified event type that are currently registered at this
    076     * object.
    077     *
    078     * @param eventType the event type object
    079     * @param <T> the event type
    080     * @return a collection with the event listeners of the specified event type (this collection is a snapshot of the
    081     *         currently registered listeners; it cannot be manipulated)
    082     */
    083    public <T extends Event> Collection<EventListener<? super T>> getEventListeners(final EventType<T> eventType) {
    084        final List<EventListener<? super T>> result = new LinkedList<>();
    085        for (final EventListener<? super T> l : eventListeners.getEventListeners(eventType)) {
    086            result.add(l);
    087        }
    088        return Collections.unmodifiableCollection(result);
    089    }
    090
    091    /**
    092     * Returns a list with all {@code EventListenerRegistrationData} objects currently contained for this event source. This
    093     * method allows access to all registered event listeners, independent on their type.
    094     *
    095     * @return a list with information about all registered event listeners
    096     */
    097    public List<EventListenerRegistrationData<?>> getEventListenerRegistrations() {
    098        return eventListeners.getRegistrations();
    099    }
    100
    101    /**
    102     * Returns a flag whether detail events are enabled.
    103     *
    104     * @return a flag if detail events are generated
    105     */
    106    public boolean isDetailEvents() {
    107        return checkDetailEvents(0);
    108    }
    109
    110    /**
    111     * Determines whether detail events should be generated. If enabled, some methods can generate multiple update events.
    112     * Note that this method records the number of calls, i.e. if for instance {@code setDetailEvents(false)} was called
    113     * three times, you will have to invoke the method as often to enable the details.
    114     *
    115     * @param enable a flag if detail events should be enabled or disabled
    116     */
    117    public void setDetailEvents(final boolean enable) {
    118        synchronized (lockDetailEventsCount) {
    119            if (enable) {
    120                detailEvents++;
    121            } else {
    122                detailEvents--;
    123            }
    124        }
    125    }
    126
    127    @Override
    128    public <T extends Event> void addEventListener(final EventType<T> eventType, final EventListener<? super T> listener) {
    129        eventListeners.addEventListener(eventType, listener);
    130    }
    131
    132    @Override
    133    public <T extends Event> boolean removeEventListener(final EventType<T> eventType, final EventListener<? super T> listener) {
    134        return eventListeners.removeEventListener(eventType, listener);
    135    }
    136
    137    /**
    138     * Removes all registered event listeners.
    139     */
    140    public void clearEventListeners() {
    141        eventListeners.clear();
    142    }
    143
    144    /**
    145     * Removes all registered error listeners.
    146     *
    147     * @since 1.4
    148     */
    149    public void clearErrorListeners() {
    150        for (final EventListenerRegistrationData<? extends ConfigurationErrorEvent> reg : eventListeners
    151            .getRegistrationsForSuperType(ConfigurationErrorEvent.ANY)) {
    152            eventListeners.removeEventListener(reg);
    153        }
    154    }
    155
    156    /**
    157     * Copies all event listener registrations maintained by this object to the specified {@code BaseEventSource} object.
    158     *
    159     * @param source the target source for the copy operation (must not be <b>null</b>)
    160     * @throws IllegalArgumentException if the target source is <b>null</b>
    161     * @since 2.0
    162     */
    163    public void copyEventListeners(final BaseEventSource source) {
    164        if (source == null) {
    165            throw new IllegalArgumentException("Target event source must not be null!");
    166        }
    167        source.eventListeners.addAll(eventListeners);
    168    }
    169
    170    /**
    171     * Creates an event object and delivers it to all registered event listeners. The method checks first if sending an
    172     * event is allowed (making use of the {@code detailEvents} property), and if listeners are registered.
    173     *
    174     * @param type the event's type
    175     * @param propName the name of the affected property (can be <b>null</b>)
    176     * @param propValue the value of the affected property (can be <b>null</b>)
    177     * @param before the before update flag
    178     * @param <T> the type of the event to be fired
    179     */
    180    protected <T extends ConfigurationEvent> void fireEvent(final EventType<T> type, final String propName, final Object propValue, final boolean before) {
    181        if (checkDetailEvents(-1)) {
    182            final EventListenerList.EventListenerIterator<T> it = eventListeners.getEventListenerIterator(type);
    183            if (it.hasNext()) {
    184                final ConfigurationEvent event = createEvent(type, propName, propValue, before);
    185                while (it.hasNext()) {
    186                    it.invokeNext(event);
    187                }
    188            }
    189        }
    190    }
    191
    192    /**
    193     * Creates a {@code ConfigurationEvent} object based on the passed in parameters. This method is called by
    194     * {@code fireEvent()} if it decides that an event needs to be generated.
    195     *
    196     * @param type the event's type
    197     * @param propName the name of the affected property (can be <b>null</b>)
    198     * @param propValue the value of the affected property (can be <b>null</b>)
    199     * @param before the before update flag
    200     * @param <T> the type of the event to be created
    201     * @return the newly created event object
    202     */
    203    protected <T extends ConfigurationEvent> ConfigurationEvent createEvent(final EventType<T> type, final String propName, final Object propValue,
    204        final boolean before) {
    205        return new ConfigurationEvent(this, type, propName, propValue, before);
    206    }
    207
    208    /**
    209     * Creates an error event object and delivers it to all registered error listeners of a matching type.
    210     *
    211     * @param eventType the event's type
    212     * @param operationType the type of the failed operation
    213     * @param propertyName the name of the affected property (can be <b>null</b>)
    214     * @param propertyValue the value of the affected property (can be <b>null</b>)
    215     * @param cause the {@code Throwable} object that caused this error event
    216     * @param <T> the event type
    217     */
    218    public <T extends ConfigurationErrorEvent> void fireError(final EventType<T> eventType, final EventType<?> operationType, final String propertyName,
    219        final Object propertyValue, final Throwable cause) {
    220        final EventListenerList.EventListenerIterator<T> iterator = eventListeners.getEventListenerIterator(eventType);
    221        if (iterator.hasNext()) {
    222            final ConfigurationErrorEvent event = createErrorEvent(eventType, operationType, propertyName, propertyValue, cause);
    223            while (iterator.hasNext()) {
    224                iterator.invokeNext(event);
    225            }
    226        }
    227    }
    228
    229    /**
    230     * Creates a {@code ConfigurationErrorEvent} object based on the passed in parameters. This is called by
    231     * {@code fireError()} if it decides that an event needs to be generated.
    232     *
    233     * @param type the event's type
    234     * @param opType the operation type related to this error
    235     * @param propName the name of the affected property (can be <b>null</b>)
    236     * @param propValue the value of the affected property (can be <b>null</b>)
    237     * @param ex the {@code Throwable} object that caused this error event
    238     * @return the event object
    239     */
    240    protected ConfigurationErrorEvent createErrorEvent(final EventType<? extends ConfigurationErrorEvent> type, final EventType<?> opType,
    241        final String propName, final Object propValue, final Throwable ex) {
    242        return new ConfigurationErrorEvent(this, type, opType, propName, propValue, ex);
    243    }
    244
    245    /**
    246     * Overrides the {@code clone()} method to correctly handle so far registered event listeners. This implementation
    247     * ensures that the clone will have empty event listener lists, i.e. the listeners registered at an
    248     * {@code BaseEventSource} object will not be copied.
    249     *
    250     * @return the cloned object
    251     * @throws CloneNotSupportedException if cloning is not allowed
    252     * @since 1.4
    253     */
    254    @Override
    255    protected Object clone() throws CloneNotSupportedException {
    256        final BaseEventSource copy = (BaseEventSource) super.clone();
    257        copy.initListeners();
    258        return copy;
    259    }
    260
    261    /**
    262     * Initializes the collections for storing registered event listeners.
    263     */
    264    private void initListeners() {
    265        eventListeners = new EventListenerList();
    266    }
    267
    268    /**
    269     * Helper method for checking the current counter for detail events. This method checks whether the counter is greater
    270     * than the passed in limit.
    271     *
    272     * @param limit the limit to be compared to
    273     * @return <b>true</b> if the counter is greater than the limit, <b>false</b> otherwise
    274     */
    275    private boolean checkDetailEvents(final int limit) {
    276        synchronized (lockDetailEventsCount) {
    277            return detailEvents > limit;
    278        }
    279    }
    280}