View Javadoc
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    *     https://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.builder;
18  
19  import java.util.Collection;
20  import java.util.Collections;
21  import java.util.HashMap;
22  import java.util.Map;
23  
24  import org.apache.commons.configuration2.ConfigurationUtils;
25  import org.apache.commons.configuration2.ImmutableConfiguration;
26  import org.apache.commons.configuration2.Initializable;
27  import org.apache.commons.configuration2.beanutils.BeanDeclaration;
28  import org.apache.commons.configuration2.beanutils.BeanHelper;
29  import org.apache.commons.configuration2.beanutils.ConstructorArg;
30  import org.apache.commons.configuration2.event.Event;
31  import org.apache.commons.configuration2.event.EventListener;
32  import org.apache.commons.configuration2.event.EventListenerList;
33  import org.apache.commons.configuration2.event.EventListenerRegistrationData;
34  import org.apache.commons.configuration2.event.EventSource;
35  import org.apache.commons.configuration2.event.EventType;
36  import org.apache.commons.configuration2.ex.ConfigurationException;
37  import org.apache.commons.configuration2.ex.ConfigurationRuntimeException;
38  import org.apache.commons.configuration2.reloading.ReloadingController;
39  
40  /**
41   * <p>
42   * An implementation of the {@code ConfigurationBuilder} interface which is able to create different concrete
43   * {@code ImmutableConfiguration} implementations based on reflection.
44   * </p>
45   * <p>
46   * When constructing an instance of this class the concrete {@code ImmutableConfiguration} implementation class has to
47   * be provided. Then properties for the new {@code ImmutableConfiguration} instance can be set. The first call to
48   * {@code getConfiguration()} creates and initializes the new {@code ImmutableConfiguration} object. It is cached and
49   * returned by subsequent calls. This cache - and also the initialization properties set so far - can be flushed by
50   * calling one of the {@code reset()} methods. That way other {@code ImmutableConfiguration} instances with different
51   * properties can be created.
52   * </p>
53   * <p>
54   * If the newly created {@code ImmutableConfiguration} object implements the {@code Initializable} interface, its
55   * {@code initialize()} method is called after all initialization properties have been set. This way a concrete
56   * implementation class can perform arbitrary initialization steps.
57   * </p>
58   * <p>
59   * There are multiple options for setting up a {@code BasicConfigurationBuilder} instance:
60   * </p>
61   * <ul>
62   * <li>All initialization properties can be set in one or multiple calls of the {@code configure()} method. In each call
63   * an arbitrary number of {@link BuilderParameters} objects can be passed. The API allows method chaining and is
64   * intended to be used from Java code.</li>
65   * <li>If builder instances are created by other means - for example using a dependency injection framework -, the fluent API
66   * approach may not be suitable. For those use cases it is also possible to pass in all initialization parameters as a
67   * map. The keys of the map have to match initialization properties of the {@code ImmutableConfiguration} object to be
68   * created, the values are the corresponding property values. For instance, the key <em>throwExceptionOnMissing</em> in
69   * the map will cause the method {@code setThrowExceptionOnMissing()} on the {@code ImmutableConfiguration} object to be
70   * called with the corresponding value as parameter.</li>
71   * </ul>
72   * <p>
73   * A builder instance can be constructed with an <em>allowFailOnInit</em> flag. If set to <strong>true</strong>,
74   * exceptions during initialization of the configuration are ignored; in such a case an empty configuration object is
75   * returned. A use case for this flag is a scenario in which a configuration is optional and created on demand the first
76   * time configuration data is to be stored. Consider an application that stores user-specific configuration data in the
77   * user's home directory: When started for the first time by a new user there is no configuration file; so it makes
78   * sense to start with an empty configuration object. On application exit, settings can be stored in this object and
79   * written to the associated file. Then they are available on next application start.
80   * </p>
81   * <p>
82   * This class is thread-safe. Multiple threads can modify initialization properties and call {@code getConfiguration()}.
83   * However, the intended use case is that the builder is configured by a single thread first. Then
84   * {@code getConfiguration()} can be called concurrently, and it is guaranteed that always the same
85   * {@code ImmutableConfiguration} instance is returned until the builder is reset.
86   * </p>
87   *
88   * @param <T> the concrete type of {@code ImmutableConfiguration} objects created by this builder
89   * @since 2.0
90   */
91  public class BasicConfigurationBuilder<T extends ImmutableConfiguration> implements ConfigurationBuilder<T> {
92      /**
93       * Registers an event listener at an event source object.
94       *
95       * @param evSrc the event source
96       * @param regData the registration data object
97       * @param <E> the type of the event listener
98       */
99      private static <E extends Event> void registerListener(final EventSource evSrc, final EventListenerRegistrationData<E> regData) {
100         evSrc.addEventListener(regData.getEventType(), regData.getListener());
101     }
102 
103     /**
104      * Removes an event listener from an event source object.
105      *
106      * @param evSrc the event source
107      * @param regData the registration data object
108      * @param <E> the type of the event listener
109      */
110     private static <E extends Event> void removeListener(final EventSource evSrc, final EventListenerRegistrationData<E> regData) {
111         evSrc.removeEventListener(regData.getEventType(), regData.getListener());
112     }
113 
114     /** The class of the objects produced by this builder instance. */
115     private final Class<? extends T> resultClass;
116 
117     /** An object managing the event listeners registered at this builder. */
118     private final EventListenerList eventListeners;
119 
120     /** A flag whether exceptions on initializing configurations are allowed. */
121     private final boolean allowFailOnInit;
122 
123     /** The map with current initialization parameters. */
124     private Map<String, Object> parameters;
125 
126     /** The current bean declaration. */
127     private BeanDeclaration resultDeclaration;
128 
129     /** The result object of this builder. */
130     private volatile T result;
131 
132     /**
133      * Creates a new instance of {@code BasicConfigurationBuilder} and initializes it with the given result class. No
134      * initialization properties are set.
135      *
136      * @param resCls the result class (must not be <strong>null</strong>)
137      * @throws IllegalArgumentException if the result class is <strong>null</strong>
138      */
139     public BasicConfigurationBuilder(final Class<? extends T> resCls) {
140         this(resCls, null);
141     }
142 
143     /**
144      * Creates a new instance of {@code BasicConfigurationBuilder} and initializes it with the given result class and an
145      * initial set of builder parameters. The <em>allowFailOnInit</em> flag is set to <strong>false</strong>.
146      *
147      * @param resCls the result class (must not be <strong>null</strong>)
148      * @param params a map with initialization parameters
149      * @throws IllegalArgumentException if the result class is <strong>null</strong>
150      */
151     public BasicConfigurationBuilder(final Class<? extends T> resCls, final Map<String, Object> params) {
152         this(resCls, params, false);
153     }
154 
155     /**
156      * Creates a new instance of {@code BasicConfigurationBuilder} and initializes it with the given result class, an
157      * initial set of builder parameters, and the <em>allowFailOnInit</em> flag. The map with parameters may be <strong>null</strong>,
158      * in this case no initialization parameters are set.
159      *
160      * @param resCls the result class (must not be <strong>null</strong>)
161      * @param params a map with initialization parameters
162      * @param allowFailOnInit a flag whether exceptions on initializing a newly created {@code ImmutableConfiguration}
163      *        object are allowed
164      * @throws IllegalArgumentException if the result class is <strong>null</strong>
165      */
166     public BasicConfigurationBuilder(final Class<? extends T> resCls, final Map<String, Object> params, final boolean allowFailOnInit) {
167         if (resCls == null) {
168             throw new IllegalArgumentException("Result class must not be null!");
169         }
170 
171         resultClass = resCls;
172         this.allowFailOnInit = allowFailOnInit;
173         eventListeners = new EventListenerList();
174         updateParameters(params);
175     }
176 
177     /**
178      * {@inheritDoc} This implementation also takes care that the event listener is added to the managed configuration
179      * object.
180      *
181      * @throws IllegalArgumentException if the event type or the listener is <strong>null</strong>
182      */
183     @Override
184     public <E extends Event> void addEventListener(final EventType<E> eventType, final EventListener<? super E> listener) {
185         installEventListener(eventType, listener);
186     }
187 
188     /**
189      * Adds the content of the given map to the already existing initialization parameters.
190      *
191      * @param params the map with additional initialization parameters; may be <strong>null</strong>, then this call has no effect
192      * @return a reference to this builder for method chaining
193      */
194     public synchronized BasicConfigurationBuilder<T> addParameters(final Map<String, Object> params) {
195         final Map<String, Object> newParams = new HashMap<>(getParameters());
196         if (params != null) {
197             newParams.putAll(params);
198         }
199         updateParameters(newParams);
200         return this;
201     }
202 
203     /**
204      * Checks whether the class of the result configuration is compatible with this builder's result class. This is done to
205      * ensure that only objects of the expected result class are created.
206      *
207      * @param inst the result instance to be checked
208      * @throws ConfigurationRuntimeException if an invalid result class is detected
209      */
210     private void checkResultInstance(final Object inst) {
211         if (!getResultClass().isInstance(inst)) {
212             throw new ConfigurationRuntimeException("Incompatible result object: " + inst);
213         }
214     }
215 
216     /**
217      * Appends the content of the specified {@code BuilderParameters} objects to the current initialization parameters.
218      * Calling this method multiple times will create a union of the parameters provided.
219      *
220      * @param params an arbitrary number of objects with builder parameters
221      * @return a reference to this builder for method chaining
222      * @throws NullPointerException if a <strong>null</strong> array is passed
223      */
224     public BasicConfigurationBuilder<T> configure(final BuilderParameters... params) {
225         final Map<String, Object> newParams = new HashMap<>();
226         for (final BuilderParameters p : params) {
227             newParams.putAll(p.getParameters());
228             handleEventListenerProviders(p);
229         }
230         return setParameters(newParams);
231     }
232 
233     /**
234      * Connects this builder with a {@code ReloadingController}. With this method support for reloading can be added to an
235      * arbitrary builder object. Event listeners are registered at the reloading controller and this builder with connect
236      * both objects:
237      * <ul>
238      * <li>When the reloading controller detects that a reload is required, the builder's {@link #resetResult()} method is
239      * called; so the managed result object is invalidated.</li>
240      * <li>When a new result object has been created the controller's reloading state is reset, so that new changes can be
241      * detected again.</li>
242      * </ul>
243      *
244      * @param controller the {@code ReloadingController} to connect to (must not be <strong>null</strong>)
245      * @throws IllegalArgumentException if the controller is <strong>null</strong>
246      */
247     public final void connectToReloadingController(final ReloadingController controller) {
248         if (controller == null) {
249             throw new IllegalArgumentException("ReloadingController must not be null!");
250         }
251         ReloadingBuilderSupportListener.connect(this, controller);
252     }
253 
254     /**
255      * Copies all {@code EventListener} objects registered at this builder to the specified target configuration builder.
256      * This method is intended to be used by derived classes which support inheritance of their properties to other builder
257      * objects.
258      *
259      * @param target the target configuration builder (must not be <strong>null</strong>)
260      * @throws NullPointerException if the target builder is <strong>null</strong>
261      */
262     protected synchronized void copyEventListeners(final BasicConfigurationBuilder<?> target) {
263         copyEventListeners(target, eventListeners);
264     }
265 
266     /**
267      * Copies all event listeners in the specified list to the specified target configuration builder. This method is
268      * intended to be used by derived classes which have to deal with managed configuration builders that need to be
269      * initialized with event listeners.
270      *
271      * @param target the target configuration builder (must not be <strong>null</strong>)
272      * @param listeners the event listeners to be copied over
273      * @throws NullPointerException if the target builder is <strong>null</strong>
274      */
275     protected void copyEventListeners(final BasicConfigurationBuilder<?> target, final EventListenerList listeners) {
276         target.eventListeners.addAll(listeners);
277     }
278 
279     /**
280      * Creates a new, initialized result object. This method is called by {@code getConfiguration()} if no valid result
281      * object exists. This base implementation performs two steps:
282      * <ul>
283      * <li>{@code createResultInstance()} is called to create a new, uninitialized result object.</li>
284      * <li>{@code initResultInstance()} is called to process all initialization parameters.</li>
285      * </ul>
286      * It also evaluates the <em>allowFailOnInit</em> flag, i.e. if initialization causes an exception and this flag is set,
287      * the exception is ignored, and the newly created, uninitialized configuration is returned. Note that this method is
288      * called in a synchronized block.
289      *
290      * @return the newly created result object
291      * @throws ConfigurationException if an error occurs
292      */
293     protected T createResult() throws ConfigurationException {
294         final T resObj = createResultInstance();
295 
296         try {
297             initResultInstance(resObj);
298         } catch (final ConfigurationException cex) {
299             if (!isAllowFailOnInit()) {
300                 throw cex;
301             }
302         }
303 
304         return resObj;
305     }
306 
307     /**
308      * Creates a new {@code BeanDeclaration} which is used for creating new result objects dynamically. This implementation
309      * creates a specialized {@code BeanDeclaration} object that is initialized from the given map of initialization
310      * parameters. The {@code BeanDeclaration} must be initialized with the result class of this builder, otherwise
311      * exceptions will be thrown when the result object is created. Note: This method is invoked in a synchronized block.
312      *
313      * @param params a snapshot of the current initialization parameters
314      * @return the {@code BeanDeclaration} for creating result objects
315      * @throws ConfigurationException if an error occurs
316      */
317     protected BeanDeclaration createResultDeclaration(final Map<String, Object> params) throws ConfigurationException {
318         return new BeanDeclaration() {
319             @Override
320             public String getBeanClassName() {
321                 return getResultClass().getName();
322             }
323 
324             @Override
325             public String getBeanFactoryName() {
326                 return null;
327             }
328 
329             @Override
330             public Object getBeanFactoryParameter() {
331                 return null;
332             }
333 
334             @Override
335             public Map<String, Object> getBeanProperties() {
336                 // the properties are equivalent to the parameters
337                 return params;
338             }
339 
340             @Override
341             public Collection<ConstructorArg> getConstructorArgs() {
342                 // no constructor arguments
343                 return Collections.emptySet();
344             }
345 
346             @Override
347             public Map<String, Object> getNestedBeanDeclarations() {
348                 // no nested beans
349                 return Collections.emptyMap();
350             }
351         };
352     }
353 
354     /**
355      * Creates the new, uninitialized result object. This is the first step of the process of producing a result object for
356      * this builder. This implementation uses the {@link BeanHelper} class to create a new object based on the
357      * {@link BeanDeclaration} returned by {@link #getResultDeclaration()}. Note: This method is invoked in a synchronized
358      * block.
359      *
360      * @return the newly created, yet uninitialized result object
361      * @throws ConfigurationException if an exception occurs
362      */
363     protected T createResultInstance() throws ConfigurationException {
364         final Object bean = fetchBeanHelper().createBean(getResultDeclaration());
365         checkResultInstance(bean);
366         return getResultClass().cast(bean);
367     }
368 
369     /**
370      * Obtains the {@code BeanHelper} object to be used when dealing with bean declarations. This method checks whether this
371      * builder was configured with a specific {@code BeanHelper} instance. If so, this instance is used. Otherwise, the
372      * default {@code BeanHelper} is returned.
373      *
374      * @return the {@code BeanHelper} to be used
375      */
376     protected final BeanHelper fetchBeanHelper() {
377         final BeanHelper helper = BasicBuilderParameters.fetchBeanHelper(getParameters());
378         return helper != null ? helper : BeanHelper.INSTANCE;
379     }
380 
381     /**
382      * Returns an {@code EventSource} for the current result object. If there is no current result or if it does not extend
383      * {@code EventSource}, a dummy event source is returned.
384      *
385      * @return the {@code EventSource} for the current result object
386      */
387     private EventSource fetchEventSource() {
388         return ConfigurationUtils.asEventSource(result, true);
389     }
390 
391     /**
392      * Sends the specified builder event to all registered listeners.
393      *
394      * @param event the event to be fired
395      */
396     protected void fireBuilderEvent(final ConfigurationBuilderEvent event) {
397         eventListeners.fire(event);
398     }
399 
400     /**
401      * {@inheritDoc} This implementation creates the result configuration on first access. Later invocations return the same
402      * object until this builder is reset. The double-check idiom for lazy initialization is used (Bloch, Effective Java,
403      * item 71).
404      */
405     @Override
406     public T getConfiguration() throws ConfigurationException {
407         fireBuilderEvent(new ConfigurationBuilderEvent(this, ConfigurationBuilderEvent.CONFIGURATION_REQUEST));
408 
409         T resObj = result;
410         boolean created = false;
411         if (resObj == null) {
412             synchronized (this) {
413                 resObj = result;
414                 if (resObj == null) {
415                     result = resObj = createResult();
416                     created = true;
417                 }
418             }
419         }
420 
421         if (created) {
422             fireBuilderEvent(new ConfigurationBuilderResultCreatedEvent(this, ConfigurationBuilderResultCreatedEvent.RESULT_CREATED, resObj));
423         }
424         return resObj;
425     }
426 
427     /**
428      * Gets a map with initialization parameters where all parameters starting with the reserved prefix have been
429      * filtered out.
430      *
431      * @return the filtered parameters map
432      */
433     private Map<String, Object> getFilteredParameters() {
434         final Map<String, Object> filteredMap = new HashMap<>(getParameters());
435         filteredMap.keySet().removeIf(key -> key.startsWith(BuilderParameters.RESERVED_PARAMETER_PREFIX));
436         return filteredMap;
437     }
438 
439     /**
440      * Gets a (unmodifiable) map with the current initialization parameters set for this builder. The map is populated
441      * with the parameters set using the various configuration options.
442      *
443      * @return a map with the current set of initialization parameters
444      */
445     protected final synchronized Map<String, Object> getParameters() {
446         if (parameters != null) {
447             return parameters;
448         }
449         return Collections.emptyMap();
450     }
451 
452     /**
453      * Gets the result class of this builder. The objects produced by this builder have the class returned here.
454      *
455      * @return the result class of this builder
456      */
457     public Class<? extends T> getResultClass() {
458         return resultClass;
459     }
460 
461     /**
462      * Gets the {@code BeanDeclaration} that is used to create and initialize result objects. The declaration is created
463      * on first access (by invoking {@link #createResultDeclaration(Map)}) based on the current initialization parameters.
464      *
465      * @return the {@code BeanDeclaration} for dynamically creating a result object
466      * @throws ConfigurationException if an error occurs
467      */
468     protected final synchronized BeanDeclaration getResultDeclaration() throws ConfigurationException {
469         if (resultDeclaration == null) {
470             resultDeclaration = createResultDeclaration(getFilteredParameters());
471         }
472         return resultDeclaration;
473     }
474 
475     /**
476      * Checks whether the specified parameters object implements the {@code EventListenerProvider} interface. If so, the
477      * event listeners it provides are added to this builder.
478      *
479      * @param params the parameters object
480      */
481     private void handleEventListenerProviders(final BuilderParameters params) {
482         if (params instanceof EventListenerProvider) {
483             eventListeners.addAll(((EventListenerProvider) params).getListeners());
484         }
485     }
486 
487     /**
488      * Performs special initialization of the result object. This method is called after parameters have been set on a newly
489      * created result instance. If supported by the result class, the {@code initialize()} method is now called.
490      *
491      * @param obj the newly created result object
492      */
493     private void handleInitializable(final T obj) {
494         if (obj instanceof Initializable) {
495             ((Initializable) obj).initialize();
496         }
497     }
498 
499     /**
500      * Initializes a newly created result object. This is the second step of the process of producing a result object for
501      * this builder. This implementation uses the {@link BeanHelper} class to initialize the object's property based on the
502      * {@link BeanDeclaration} returned by {@link #getResultDeclaration()}. Note: This method is invoked in a synchronized
503      * block. This is required because internal state is accessed. Sub classes must not call this method without proper
504      * synchronization.
505      *
506      * @param obj the object to be initialized
507      * @throws ConfigurationException if an error occurs
508      */
509     protected void initResultInstance(final T obj) throws ConfigurationException {
510         fetchBeanHelper().initBean(obj, getResultDeclaration());
511         registerEventListeners(obj);
512         handleInitializable(obj);
513     }
514 
515     /**
516      * Adds the specified event listener to this object. This method is called by {@code addEventListener()}, it does the
517      * actual listener registration. Because it is final it can be called by sub classes in the constructor if there is
518      * already the need to register an event listener.
519      *
520      * @param eventType the event type object
521      * @param listener the listener to be registered
522      * @param <E> the event type
523      */
524     protected final <E extends Event> void installEventListener(final EventType<E> eventType, final EventListener<? super E> listener) {
525         fetchEventSource().addEventListener(eventType, listener);
526         eventListeners.addEventListener(eventType, listener);
527     }
528 
529     /**
530      * Returns the <em>allowFailOnInit</em> flag. See the header comment for information about this flag.
531      *
532      * @return the <em>allowFailOnInit</em> flag
533      */
534     public boolean isAllowFailOnInit() {
535         return allowFailOnInit;
536     }
537 
538     /**
539      * Registers the available event listeners at the given object. This method is called for each result object created by
540      * the builder.
541      *
542      * @param obj the object to initialize
543      */
544     private void registerEventListeners(final T obj) {
545         final EventSource evSrc = ConfigurationUtils.asEventSource(obj, true);
546         eventListeners.getRegistrations().forEach(regData -> registerListener(evSrc, regData));
547     }
548 
549     /**
550      * {@inheritDoc} This implementation also takes care that the event listener is removed from the managed configuration
551      * object.
552      */
553     @Override
554     public <E extends Event> boolean removeEventListener(final EventType<E> eventType, final EventListener<? super E> listener) {
555         fetchEventSource().removeEventListener(eventType, listener);
556         return eventListeners.removeEventListener(eventType, listener);
557     }
558 
559     /**
560      * Removes all available event listeners from the given result object. This method is called when the result of this
561      * builder is reset. Then the old managed configuration should no longer generate events.
562      *
563      * @param obj the affected result object
564      */
565     private void removeEventListeners(final T obj) {
566         final EventSource evSrc = ConfigurationUtils.asEventSource(obj, true);
567         eventListeners.getRegistrations().forEach(regData -> removeListener(evSrc, regData));
568     }
569 
570     /**
571      * Resets this builder. This is a convenience method which combines calls to {@link #resetResult()} and
572      * {@link #resetParameters()}.
573      */
574     public synchronized void reset() {
575         resetParameters();
576         resetResult();
577     }
578 
579     /**
580      * Removes all initialization parameters of this builder. This method can be called if this builder is to be reused for
581      * creating result objects with a different configuration.
582      */
583     public void resetParameters() {
584         setParameters(null);
585     }
586 
587     /**
588      * Clears an existing result object. An invocation of this method causes a new {@code ImmutableConfiguration} object to
589      * be created the next time {@link #getConfiguration()} is called.
590      */
591     public void resetResult() {
592         final T oldResult;
593         synchronized (this) {
594             oldResult = result;
595             result = null;
596             resultDeclaration = null;
597         }
598 
599         if (oldResult != null) {
600             removeEventListeners(oldResult);
601         }
602         fireBuilderEvent(new ConfigurationBuilderEvent(this, ConfigurationBuilderEvent.RESET));
603     }
604 
605     /**
606      * Sets the initialization parameters of this builder. Already existing parameters are replaced by the content of the
607      * given map.
608      *
609      * @param params the new initialization parameters of this builder; can be <strong>null</strong>, then all initialization
610      *        parameters are removed
611      * @return a reference to this builder for method chaining
612      */
613     public synchronized BasicConfigurationBuilder<T> setParameters(final Map<String, Object> params) {
614         updateParameters(params);
615         return this;
616     }
617 
618     /**
619      * Replaces the current map with parameters by a new one.
620      *
621      * @param newParams the map with new parameters (may be <strong>null</strong>)
622      */
623     private void updateParameters(final Map<String, Object> newParams) {
624         final Map<String, Object> map = new HashMap<>();
625         if (newParams != null) {
626             map.putAll(newParams);
627         }
628         parameters = Collections.unmodifiableMap(map);
629     }
630 }