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.combined;
018
019import java.lang.reflect.Constructor;
020import java.util.ArrayList;
021import java.util.Collection;
022import java.util.Collections;
023import java.util.Map;
024
025import org.apache.commons.configuration2.Configuration;
026import org.apache.commons.configuration2.ConfigurationUtils;
027import org.apache.commons.configuration2.builder.BasicConfigurationBuilder;
028import org.apache.commons.configuration2.builder.BuilderParameters;
029import org.apache.commons.configuration2.builder.ConfigurationBuilder;
030import org.apache.commons.configuration2.ex.ConfigurationException;
031
032/**
033 * <p>
034 * A fully-functional, reflection-based implementation of the {@code ConfigurationBuilderProvider} interface which can
035 * deal with the default tags defining configuration sources.
036 * </p>
037 * <p>
038 * An instance of this class is initialized with the names of the {@code ConfigurationBuilder} class used by this
039 * provider and the concrete {@code Configuration} class. The {@code ConfigurationBuilder} class must be derived from
040 * {@link BasicConfigurationBuilder}. When asked for the builder object, an instance of the builder class is created and
041 * initialized from the bean declaration associated with the current configuration source.
042 * </p>
043 * <p>
044 * {@code ConfigurationBuilder} objects are configured using parameter objects. When declaring configuration sources in
045 * XML it should not be necessary to define the single parameter objects. Rather, simple and complex properties are set
046 * in the typical way of a bean declaration (i.e. as attributes of the current XML element or as child elements). This
047 * class creates all supported parameter objects (whose names also must be provided at construction time) and takes care
048 * that their properties are initialized according to the current bean declaration.
049 * </p>
050 * <p>
051 * The use of reflection to create builder instances allows a generic implementation supporting many concrete builder
052 * classes. Another reason for this approach is that builder classes are only loaded if actually needed. Some
053 * specialized {@code Configuration} implementations require specific external dependencies which should not be
054 * mandatory for the use of {@code CombinedConfigurationBuilder}. Because such classes are lazily loaded, an application
055 * only has to include the dependencies it actually uses.
056 * </p>
057 *
058 * @since 2.0
059 */
060public class BaseConfigurationBuilderProvider implements ConfigurationBuilderProvider {
061    /** The types of the constructor parameters for a basic builder. */
062    private static final Class<?>[] CTOR_PARAM_TYPES = {Class.class, Map.class, Boolean.TYPE};
063
064    /**
065     * Creates an instance of a parameter class using reflection.
066     *
067     * @param paramcls the parameter class
068     * @return the newly created instance
069     * @throws Exception if an error occurs
070     */
071    private static BuilderParameters createParameterObject(final String paramcls) throws ReflectiveOperationException {
072        return (BuilderParameters) ConfigurationUtils.loadClass(paramcls).getConstructor().newInstance();
073    }
074
075    /**
076     * Creates a new, unmodifiable collection for the parameter classes.
077     *
078     * @param paramCls the collection with parameter classes passed to the constructor
079     * @return the collection to be stored
080     */
081    private static Collection<String> initParameterClasses(final Collection<String> paramCls) {
082        if (paramCls == null) {
083            return Collections.emptySet();
084        }
085        return Collections.unmodifiableCollection(new ArrayList<>(paramCls));
086    }
087
088    /** The name of the builder class. */
089    private final String builderClass;
090
091    /** The name of a builder class with reloading support. */
092    private final String reloadingBuilderClass;
093
094    /** Stores the name of the configuration class to be created. */
095    private final String configurationClass;
096
097    /** A collection with the names of parameter classes. */
098    private final Collection<String> parameterClasses;
099
100    /**
101     * Creates a new instance of {@code BaseConfigurationBuilderProvider} and initializes all its properties.
102     *
103     * @param bldrCls the name of the builder class (must not be <b>null</b>)
104     * @param reloadBldrCls the name of a builder class to be used if reloading support is required (<b>null</b> if
105     *        reloading is not supported)
106     * @param configCls the name of the configuration class (must not be <b>null</b>)
107     * @param paramCls a collection with the names of parameters classes
108     * @throws IllegalArgumentException if a required parameter is missing
109     */
110    public BaseConfigurationBuilderProvider(final String bldrCls, final String reloadBldrCls, final String configCls, final Collection<String> paramCls) {
111        if (bldrCls == null) {
112            throw new IllegalArgumentException("Builder class must not be null!");
113        }
114        if (configCls == null) {
115            throw new IllegalArgumentException("Configuration class must not be null!");
116        }
117
118        builderClass = bldrCls;
119        reloadingBuilderClass = reloadBldrCls;
120        configurationClass = configCls;
121        parameterClasses = initParameterClasses(paramCls);
122    }
123
124    /**
125     * Configures a newly created builder instance with its initialization parameters. This method is called after a new
126     * instance was created using reflection. This implementation passes the parameter objects to the builder's
127     * {@code configure()} method.
128     *
129     * @param builder the builder to be initialized
130     * @param decl the current {@code ConfigurationDeclaration}
131     * @param params the collection with initialization parameter objects
132     * @throws Exception if an error occurs
133     */
134    protected void configureBuilder(final BasicConfigurationBuilder<? extends Configuration> builder, final ConfigurationDeclaration decl,
135        final Collection<BuilderParameters> params) throws Exception {
136        builder.configure(params.toArray(new BuilderParameters[params.size()]));
137    }
138
139    /**
140     * Creates a new, uninitialized instance of the builder class managed by this provider. This implementation determines
141     * the builder class to be used by delegating to {@code determineBuilderClass()}. It then calls the constructor
142     * expecting the configuration class, the map with properties, and the<em>allowFailOnInit</em> flag.
143     *
144     * @param decl the current {@code ConfigurationDeclaration}
145     * @param params initialization parameters for the new builder object
146     * @return the newly created builder instance
147     * @throws Exception if an error occurs
148     */
149    protected BasicConfigurationBuilder<? extends Configuration> createBuilder(final ConfigurationDeclaration decl, final Collection<BuilderParameters> params)
150        throws Exception {
151        final Class<?> bldCls = ConfigurationUtils.loadClass(determineBuilderClass(decl));
152        final Class<?> configCls = ConfigurationUtils.loadClass(determineConfigurationClass(decl, params));
153        final Constructor<?> ctor = bldCls.getConstructor(CTOR_PARAM_TYPES);
154        // ? extends Configuration is the minimum constraint
155        @SuppressWarnings("unchecked")
156        final BasicConfigurationBuilder<? extends Configuration> builder = (BasicConfigurationBuilder<? extends Configuration>) ctor.newInstance(configCls,
157            null, isAllowFailOnInit(decl));
158        return builder;
159    }
160
161    /**
162     * Creates a collection of parameter objects to be used for configuring the builder. This method creates instances of
163     * the parameter classes passed to the constructor.
164     *
165     * @return a collection with parameter objects for the builder
166     * @throws Exception if an error occurs while creating parameter objects via reflection
167     */
168    protected Collection<BuilderParameters> createParameterObjects() throws Exception {
169        final Collection<BuilderParameters> params = new ArrayList<>(getParameterClasses().size());
170        for (final String paramcls : getParameterClasses()) {
171            params.add(createParameterObject(paramcls));
172        }
173        return params;
174    }
175
176    /**
177     * Determines the name of the class to be used for a new builder instance. This implementation selects between the
178     * normal and the reloading builder class, based on the passed in {@code ConfigurationDeclaration}. If a reloading
179     * builder is desired, but this provider has no reloading support, an exception is thrown.
180     *
181     * @param decl the current {@code ConfigurationDeclaration}
182     * @return the name of the builder class
183     * @throws ConfigurationException if the builder class cannot be determined
184     */
185    protected String determineBuilderClass(final ConfigurationDeclaration decl) throws ConfigurationException {
186        if (decl.isReload()) {
187            if (getReloadingBuilderClass() == null) {
188                throw new ConfigurationException("No support for reloading for builder class " + getBuilderClass());
189            }
190            return getReloadingBuilderClass();
191        }
192        return getBuilderClass();
193    }
194
195    /**
196     * Determines the name of the configuration class produced by the builder. This method is called when obtaining the
197     * arguments for invoking the constructor of the builder class. This implementation just returns the pre-configured
198     * configuration class name. Derived classes may determine this class name dynamically based on the passed in
199     * parameters.
200     *
201     * @param decl the current {@code ConfigurationDeclaration}
202     * @param params the collection with parameter objects
203     * @return the name of the builder's result configuration class
204     * @throws ConfigurationException if an error occurs
205     */
206    protected String determineConfigurationClass(final ConfigurationDeclaration decl, final Collection<BuilderParameters> params)
207        throws ConfigurationException {
208        return getConfigurationClass();
209    }
210
211    /**
212     * Gets the name of the class of the builder created by this provider.
213     *
214     * @return the builder class
215     */
216    public String getBuilderClass() {
217        return builderClass;
218    }
219
220    /**
221     * {@inheritDoc} This implementation delegates to some protected methods to create a new builder instance using
222     * reflection and to configure it with parameter values defined by the passed in {@code BeanDeclaration}.
223     */
224    @Override
225    public ConfigurationBuilder<? extends Configuration> getConfigurationBuilder(final ConfigurationDeclaration decl) throws ConfigurationException {
226        try {
227            final Collection<BuilderParameters> params = createParameterObjects();
228            initializeParameterObjects(decl, params);
229            final BasicConfigurationBuilder<? extends Configuration> builder = createBuilder(decl, params);
230            configureBuilder(builder, decl, params);
231            return builder;
232        } catch (final ConfigurationException cex) {
233            throw cex;
234        } catch (final Exception ex) {
235            throw new ConfigurationException(ex);
236        }
237    }
238
239    /**
240     * Gets the name of the configuration class created by the builder produced by this provider.
241     *
242     * @return the configuration class
243     */
244    public String getConfigurationClass() {
245        return configurationClass;
246    }
247
248    /**
249     * Gets an unmodifiable collection with the names of parameter classes supported by this provider.
250     *
251     * @return the parameter classes
252     */
253    public Collection<String> getParameterClasses() {
254        return parameterClasses;
255    }
256
257    /**
258     * Gets the name of the class of the builder created by this provider if the reload flag is set. If this method
259     * returns <b>null</b>, reloading builders are not supported by this provider.
260     *
261     * @return the reloading builder class
262     */
263    public String getReloadingBuilderClass() {
264        return reloadingBuilderClass;
265    }
266
267    /**
268     * Passes all parameter objects to the parent {@code CombinedConfigurationBuilder} so that properties already defined
269     * for the parent builder can be added. This method is called before the parameter objects are initialized from the
270     * definition configuration. This way properties from the parent builder are inherited, but can be overridden for child
271     * configurations.
272     *
273     * @param decl the current {@code ConfigurationDeclaration}
274     * @param params the collection with (uninitialized) parameter objects
275     */
276    protected void inheritParentBuilderProperties(final ConfigurationDeclaration decl, final Collection<BuilderParameters> params) {
277        params.forEach(p -> decl.getConfigurationBuilder().initChildBuilderParameters(p));
278    }
279
280    /**
281     * Initializes the parameter objects with data stored in the current bean declaration. This method is called before the
282     * newly created builder instance is configured with the parameter objects. It maps attributes of the bean declaration
283     * to properties of parameter objects. In addition, it invokes the parent {@code CombinedConfigurationBuilder} so that
284     * the parameters object can inherit properties already defined for this builder.
285     *
286     * @param decl the current {@code ConfigurationDeclaration}
287     * @param params the collection with (uninitialized) parameter objects
288     * @throws Exception if an error occurs
289     */
290    protected void initializeParameterObjects(final ConfigurationDeclaration decl, final Collection<BuilderParameters> params) throws Exception {
291        inheritParentBuilderProperties(decl, params);
292        final MultiWrapDynaBean wrapBean = new MultiWrapDynaBean(params);
293        decl.getConfigurationBuilder().initBean(wrapBean, decl);
294    }
295
296    /**
297     * Determines the <em>allowFailOnInit</em> flag for the newly created builder based on the given
298     * {@code ConfigurationDeclaration}. Some combinations of flags in the declaration say that a configuration source is
299     * optional, but an empty instance should be created if its creation fail.
300     *
301     * @param decl the current {@code ConfigurationDeclaration}
302     * @return the value of the <em>allowFailOnInit</em> flag
303     */
304    protected boolean isAllowFailOnInit(final ConfigurationDeclaration decl) {
305        return decl.isOptional() && decl.isForceCreate();
306    }
307}