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