    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.builder;
    018
    019import java.util.Collection;
    020import java.util.concurrent.CopyOnWriteArrayList;
    021
    022/**
    023 * <p>
    024 * A class for managing a set of {@link DefaultParametersHandler} objects.
    025 * </p>
    026 * <p>
    027 * This class provides functionality for registering and removing {@code DefaultParametersHandler} objects for arbitrary
    028 * parameters classes. The handlers registered at an instance can then be applied on a passed in parameters object, so
    029 * that it gets initialized with the provided default values.
    030 * </p>
    031 * <p>
    032 * Usage of this class is as follows: First the {@code DefaultParametersHandler} objects to be supported must be
    033 * registered using one of the {@code registerDefaultHandler()} methods. After that arbitrary parameters objects can be
    034 * passed to the {@code initializeParameters()} method. This causes all {@code DefaultParametersHandler} objects
    035 * supporting this parameters class to be invoked on this object.
    036 * </p>
    037 * <p>
    038 * Implementation note: This class is thread-safe.
    039 * </p>
    040 *
    041 * @since 2.0
    042 */
    043public class DefaultParametersManager {
    044    /**
    045     * A data class storing information about {@code DefaultParametersHandler} objects added to a {@code Parameters} object.
    046     * Using this class it is possible to find out which default handlers apply for a given parameters object and to invoke
    047     * them.
    048     */
    049    private static final class DefaultHandlerData {
    050        /** The handler object. */
    051        private final DefaultParametersHandler<?> handler;
    052
    053        /** The class supported by this handler. */
    054        private final Class<?> parameterClass;
    055
    056        /** The start class for applying this handler. */
    057        private final Class<?> startClass;
    058
    059        /**
    060         * Creates a new instance of {@code DefaultHandlerData}.
    061         *
    062         * @param h the {@code DefaultParametersHandler}
    063         * @param cls the handler's data class
    064         * @param startCls the start class
    065         */
    066        public DefaultHandlerData(final DefaultParametersHandler<?> h, final Class<?> cls, final Class<?> startCls) {
    067            handler = h;
    068            parameterClass = cls;
    069            startClass = startCls;
    070        }
    071
    072        /**
    073         * Checks whether the managed {@code DefaultParametersHandler} can be applied to the given parameters object. If this is
    074         * the case, it is executed on this object and can initialize it with default values.
    075         *
    076         * @param obj the parameters object to be initialized
    077         */
    078        @SuppressWarnings("unchecked")
    079        // There are explicit isInstance() checks, so there won't be
    080        // ClassCastExceptions
    081        public void applyHandlerIfMatching(final BuilderParameters obj) {
    082            if (parameterClass.isInstance(obj) && (startClass == null || startClass.isInstance(obj))) {
    083                @SuppressWarnings("rawtypes")
    084                final DefaultParametersHandler handlerUntyped = handler;
    085                handlerUntyped.initializeDefaults(obj);
    086            }
    087        }
    088
    089        /**
    090         * Tests whether this instance refers to the specified occurrence of a {@code DefaultParametersHandler}.
    091         *
    092         * @param h the handler to be checked
    093         * @param startCls the start class
    094         * @return <strong>true</strong> if this instance refers to this occurrence, <strong>false</strong> otherwise
    095         */
    096        public boolean isOccurrence(final DefaultParametersHandler<?> h, final Class<?> startCls) {
    097            return h == handler && (startCls == null || startCls.equals(startClass));
    098        }
    099    }
    100
    101    /** A collection with the registered default handlers. */
    102    private final Collection<DefaultHandlerData> defaultHandlers;
    103
    104    /**
    105     * Creates a new instance of {@code DefaultParametersManager}.
    106     */
    107    public DefaultParametersManager() {
    108        defaultHandlers = new CopyOnWriteArrayList<>();
    109    }
    110
    111    /**
    112     * Initializes the passed in {@code BuilderParameters} object by applying all matching {@link DefaultParametersHandler}
    113     * objects registered at this instance. Using this method the passed in parameters object can be populated with default
    114     * values.
    115     *
    116     * @param params the parameters object to be initialized (may be <strong>null</strong>, then this method has no effect)
    117     */
    118    public void initializeParameters(final BuilderParameters params) {
    119        if (params != null) {
    120            defaultHandlers.forEach(dhd -> dhd.applyHandlerIfMatching(params));
    121        }
    122    }
    123
    124    /**
    125     * Registers the specified {@code DefaultParametersHandler} object for the given parameters class. This means that this
    126     * handler object is invoked every time a parameters object of the specified class or one of its subclasses is
    127     * initialized. The handler can set arbitrary default values for the properties supported by this parameters object. If
    128     * there are multiple handlers registered supporting a specific parameters class, they are invoked in the order in which
    129     * they were registered. So handlers registered later may override the values set by handlers registered earlier.
    130     *
    131     * @param <T> the type of the parameters supported by this handler
    132     * @param paramsClass the parameters class supported by this handler (must not be <strong>null</strong>)
    133     * @param handler the {@code DefaultParametersHandler} to be registered (must not be <strong>null</strong>)
    134     * @throws IllegalArgumentException if a required parameter is missing
    135     */
    136    public <T> void registerDefaultsHandler(final Class<T> paramsClass, final DefaultParametersHandler<? super T> handler) {
    137        registerDefaultsHandler(paramsClass, handler, null);
    138    }
    139
    140    /**
    141     * Registers the specified {@code DefaultParametersHandler} object for the given parameters class and start class in the
    142     * inheritance hierarchy. This method works like {@link #registerDefaultsHandler(Class, DefaultParametersHandler)}, but
    143     * the defaults handler is only executed on parameter objects that are instances of the specified start class. Parameter
    144     * classes do not stand in a real inheritance hierarchy; however, there is a logic hierarchy defined by the methods
    145     * supported by the different parameter objects. A properties parameter object for instance supports all methods defined
    146     * for a file-based parameter object. So one can argue that
    147     * {@link org.apache.commons.configuration2.builder.fluent.FileBasedBuilderParameters FileBasedBuilderParameters} is a
    148     * base interface of {@link org.apache.commons.configuration2.builder.fluent.PropertiesBuilderParameters
    149     * PropertiesBuilderParameters} (although, for technical reasons, this relation is not reflected in the Java classes). A
    150     * {@link DefaultParametersHandler} object defined for a base interface can also deal with parameter objects "derived"
    151     * from this base interface (i.e. supporting a super set of the methods defined by the base interface). Now there may be
    152     * the use case that there is an implementation of {@code DefaultParametersHandler} for a base interface (for example
    153     * {@code FileBasedBuilderParameters}), but it should only process specific derived interfaces (say
    154     * {@code PropertiesBuilderParameters}, but not
    155     * {@link org.apache.commons.configuration2.builder.fluent.XMLBuilderParameters XMLBuilderParameters}). This can be
    156     * achieved by passing in {@code PropertiesBuilderParameters} as start class. In this case,
    157     * {@code DefaultParametersManager} ensures that the handler is only called on parameter objects having both the start
    158     * class and the actual type supported by the handler as base interfaces. The passed in start class can be <strong>null</strong>;
    159     * then the parameter class supported by the handler is used (which is the default behavior of the
    160     * {@link #registerDefaultsHandler(Class, DefaultParametersHandler)} method).
    161     *
    162     * @param <T> the type of the parameters supported by this handler
    163     * @param paramsClass the parameters class supported by this handler (must not be <strong>null</strong>)
    164     * @param handler the {@code DefaultParametersHandler} to be registered (must not be <strong>null</strong>)
    165     * @param startClass an optional start class in the hierarchy of parameter objects for which this handler should be
    166     *        applied
    167     * @throws IllegalArgumentException if a required parameter is missing
    168     */
    169    public <T> void registerDefaultsHandler(final Class<T> paramsClass, final DefaultParametersHandler<? super T> handler, final Class<?> startClass) {
    170        if (paramsClass == null) {
    171            throw new IllegalArgumentException("Parameters class must not be null!");
    172        }
    173        if (handler == null) {
    174            throw new IllegalArgumentException("DefaultParametersHandler must not be null!");
    175        }
    176        defaultHandlers.add(new DefaultHandlerData(handler, paramsClass, startClass));
    177    }
    178
    179    /**
    180     * Removes the specified {@code DefaultParametersHandler} from this instance. If this handler has been registered
    181     * multiple times for different start classes, all occurrences are removed.
    182     *
    183     * @param handler the {@code DefaultParametersHandler} to be removed
    184     */
    185    public void unregisterDefaultsHandler(final DefaultParametersHandler<?> handler) {
    186        unregisterDefaultsHandler(handler, null);
    187    }
    188
    189    /**
    190     * Removes the specified {@code DefaultParametersHandler} from this instance if it is in combination with the given
    191     * start class. If this handler has been registered multiple times for different start classes, only occurrences for the
    192     * given start class are removed. The {@code startClass} parameter can be <strong>null</strong>, then all occurrences of the
    193     * handler are removed.
    194     *
    195     * @param handler the {@code DefaultParametersHandler} to be removed
    196     * @param startClass the start class for which this handler is to be removed
    197     */
    198    public void unregisterDefaultsHandler(final DefaultParametersHandler<?> handler, final Class<?> startClass) {
    199        defaultHandlers.removeIf(dhd -> dhd.isOccurrence(handler, startClass));
    200    }
    201}